0

So I'm making a simple React app where you can search two different API's 'Recipe' and 'Movie'. I update the appState when the movie or recipe link is clicked in . For some reason, the Recipe component will not update when I search for a term the second time. The Movie component will though. I checked and the recipe Object (the list that is returned from the API request) is updated, its only the Recipe component in charge of rendering these objects that won't update unless I click away and click back (force-rerender).

I'd appreciate any help, thank you!

function App() {
    
      const [appState, setAppState] = useState('Movie')  // Updates when changing api/components
      const [searchValue, setSearchValue] = useState('')  
      const [movie, setMovieObject] = useState([])
      const [recipe, setRecipeObject] = useState([])
    
      const handleSubmit = async (event) => {
        event.preventDefault();
        if (appState === 'Movie') { const res = await MovieApi(searchValue); setMovieObject(res);}
        else if (appState === 'Recipe') { const res = await RecipeApi(searchValue); setRecipeObject(res);}
    
      }
    
      const handleSearchValue = (event) => {
        setSearchValue(event.target.value);
      }
    
      const setAppStateMovie = () => {
        setAppState('Movie')
        
      }
    
      const setAppStateRecipe = () => {
        setAppState('Recipe')
      }
    
    
      return (
        <div className={classes.app}>
          <Navigation recipeState={setAppStateRecipe} movieState={setAppStateMovie}/>
          <SearchBar
            handleSubmit={handleSubmit}
            handleSearch={handleSearchValue}
            searchState={appState}
          />
         
          <Routes>
          <Route path='/' element={<MovieComponent movie={movie} />} />
          <Route path='/recipe' element={<RecipeComponent recipe={recipe} />} />
          </Routes>
          
        </div >
      );
    }
Deland
  • 1
  • 2
  • Try to set setRecipeObject([]) also when your `appState === "Movie" ` and same for MovieObject. – MagnusEffect Feb 06 '22 at 05:52
  • @MohitMaroliyaB17CS036 That doesn't really do anything besides empty the object. – Deland Feb 06 '22 at 06:12
  • The problem may be due to React Router's unexact matching. Read more here: https://stackoverflow.com/questions/49162311/react-difference-between-route-exact-path-and-route-path. I suggest you try `} />` and see if that works – Bao Huynh Lam Feb 06 '22 at 07:06
  • @BaoHuynhLam Unfortunately, the problem still occurs. The new recipe object is definitely set, but the Recipe component does not re-render the second time I search. The strange thing is, the movie component works perfectly fine – Deland Feb 06 '22 at 19:18

0 Answers0