Oliver
Oliver

Reputation: 335

React Does Not Re-Render after useEffect and useState

React won't rerender after useEffect axios response updates state with useState. The query works, and if I click to another endpoint and back again, it does render successfully, but it doesn't successfully render on mount.

This is an expensive query so I just want to run it once when the website is loaded or refreshed.

const App: React.FC = () => {
    const [cards, setCards] = useState<Card[]>([]);

    // query server for list of cards on mount
    useEffect(() => {
        axios.get("http://localhost:3001/cards")
            .then(response => setCards(response.data))
            .catch(error => alert(`Error fetching cards. ${error}`))
    }, []);

    return (
        <Routes>
            <Route path='/' element={<LandingPage cards={cards} />} />
            {/* This does not show all cards! */}
            {cards.map((card, idx) => <Route key={idx} path={'/' + card.endpoint} element={<Card card={card}/>} />)}
        </Routes>
    )
}

Upvotes: 0

Views: 93

Answers (1)

Manuel Duarte
Manuel Duarte

Reputation: 1040

First things first, you should add a key to each element of your map function to render the Route components correctly. This will also help to force a re-render of that component whenever the keychanges. Let's try that first and see what happens

Also, the console.log(cards) after your setCards(response.data) won't print because the state update operation hasn't been finished yet

Upvotes: 1

Related Questions