Home > Back-end >  React state works for a sec upon reload, but crashes into an undefined error
React state works for a sec upon reload, but crashes into an undefined error

Time:10-24

I'm kinda new to React, and I find myself trying to code a challenge I was given. The thing is, I'm following a course of a project I already made, but using the same methodology. A searchbar and a list of results. But I get into a weird issue that I didn't have before. When testing the Code, I want to check the length of an array after a search result with axios. When reloading, the the state works well for a second, but fails to an undefined error of 'heroes' which I can't figure out by myself. I only got it to work if I use conditional rendering, and I don't even know why it works when I change {heroes.length} to {heroes && heroes.length} , but it creates another problem when trying to map the list of names and the state does not apply either. So its a dead end. setHeroes is where the issue is but don't know why that is.

import SearchBar from "./SearchBar";
import superApi from "./api/superApi";


function Home() {
  const [heroes, setHeroes] = useState([]);

  useEffect(() => {
    onTermSubmit();
  }, []);

  const onTermSubmit = async (hero) => {
    const response = await superApi.get(`/search/${hero}`);

    console.log(response.data.results);

    setHeroes(response.data.results);
  
  };

  return (
    <div>
      <SearchBar onFormSubmit={onTermSubmit} />
      There are {heroes.length} heroes with that name
    </div>
  );
}

export default Home;

CodePudding user response:

I think the problem is with the async function.

I seems your response is undefined(or response.data.results).

That's why when you use heroes && heroes.length application doesn't crash since it never runs the length method.

If you can post your console.log result i can help further

CodePudding user response:

instead of setting state value directly without checking

setHeroes(response.data.results);

Check using optional chaining and null coalescing operator.

setHeroes(response?.data?.results ?? []);

or

if (response && response.data && Array.isArray(response.data)) {

  setHeroes(response.data.results);

}
  • Related