Form not submitting until second button press

Hi all,

I am working on the Reddit API React Redux project and have run into a bit of a problem with form submission.

Project link: https://www.codecademy.com/paths/front-end-engineer-career-path/tracks/fecp-22-portfolio-project-reddit-client/modules/wdcp-22-reddit-client/kanban_projects/reddit-client

When I press enter to search for a subreddit which is later passed into a fetch request, the form submits the previous value instead of what is in the box at the current moment. I feel like this is an issue with when the state is being updated but I can’t seem to work out what I am doing wrong (probably something really simple as I can’t find anyone else with this issue…).

I put together the application using React first and had everything working fine before trying to refactor it to use Redux as I am much less confident with Redux. Below I will include the files that I believe the issue is occurring in, but if you need to see more please ask.

Appslice.js

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { setTiles } from './api';

export const setPosts = createAsyncThunk(
    'tileListSlice/setPosts',
    async (query, thunkAPI) => {
        const response = await setTiles(query);
        return response
    }
)

export const appSlice = createSlice({
    name: 'app',
    initialState: {
        query: '',
        tiles: [],
        isLoading: false,
        hasError: false
    },
    reducers: {
        setFilteredPosts: (state, action) => { state.tiles.push(action.payload); console.log(`setting filtered posts by ${action.payload}   : ${state.tiles}`) },
        updateQuery: (state, action) => { state.query = action.payload; }
    },
    extraReducers: {
        [setPosts.pending]: (state, action) => {
            state.isLoading = true;
            state.hasError = false;
        },
        [setPosts.fulfilled]: (state, action) => {
            state.isLoading = false;
            state.hasError = false;
            state.tiles = action.payload;
        },
        [setPosts.rejected]: (state, action) => {
            state.isLoading = false;
            state.hasError = true;
            state.query = `${action.payload} is not a valid subreddit`
        }
    }

})
export const selectTiles = (state) => state.app.tiles;

export const selectQuery = (state) => state.app.query;
export const { updateQuery, setFilteredPosts } = appSlice.actions;

export default appSlice.reducer;

api.js

export const transformTileData = (post) => {
    const itemUrl = post.data.url;
    return ({
        key: post.data.id,
        title: post.data.title,
        author: post.data.author,
        num_comments: post.data.num_comments,
        image: itemUrl.includes('.jpg' || '.png' || '.gif') ? itemUrl : undefined,
        link: itemUrl,
        votes: post.data.score,
        comments: post.data.permalink
    })
}

export const setTiles = async (query) => {
        console.log('Setting Tiles')
        const response = await fetch(`https://www.reddit.com/r/${query}/top.json`);
        // const jsonStringified = JSON.stringify(response);
        const json = response.json();
        // console.log(json);
        const data = json.children;
        // console.log(data);
        return data;
        // .then((data) => { return data/*data.children.map(post => transformTileData(post))*/ })
        // .then(console.log(data))
}

searchTerm.js

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';


import { setFilteredPosts, selectQuery, updateQuery } from '../../AppSlice';
import { } from './SearchTermSlice';

export default function SearchTerm() {

    const dispatch = useDispatch();
    const query = useSelector(selectQuery);

    const handleSubmit = (e) => {
        if (e.key === 'Enter') {
            dispatch(updateQuery(e.target.value));
            // dispatch(setFilteredPosts(query));
            
        }
        console.log(query);
    }


    return (
        <div>
            <input name='searchBar' type='text' placeholder='Search' id='queryBox' onKeyUp={handleSubmit}></input>
        </div>
    )
}

I am sure there are also many glaring errors and areas of bad practice in my code so please forgive me and guide me if you see anything particularly offensive.

I have commented out the link to the fetch request as the problem I am trying to solve occurs before this.

Any help would be much appreciated.

Thanks!

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile: