skip to Main Content

My useEffect doesn’t seem to work on first render so the data that I need from the api is not passed to the other components. This means I get an error

import "./App.css";
import api from "./api/axiosConfig";
import { useState, useEffect } from "react";
import Layout from "./components/Layout";
import { Routes, Route } from "react-router-dom";
import Home from "./components/home/Home";

function App() {
  const [items, setItems] = useState();

  const getItems = async () => {
    try {
      const response = await api.get("/api/v1/items");

      const itemsList = response.data.splice(10, 20);

      console.log(itemsList);

      setItems(itemsList);
    } catch (error) {
      console.log(error);
    }
  };

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

  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route path="/" element={<Home items={items} />}></Route>
        </Route>
      </Routes>
    </div>
  );
}

export default App;

Not sure what to do. Hvae been struggling for a while on this.

2

Answers


  1. I’m assuming in your Home component you’re mapping over "items", but it’s initially undefined while you wait for your data to be fetched.

    Since you can’t map over something that’s undefined, it’ll throw an error.

    You should be able to fix this by conditionally rendering your list of items in Home, something like:

    {items ? items.map((item, index) => (
        <p key={index}>{item}</p>
      )) : <p>Loading...</p>}
    

    Or you can initialize "items" as an empty array in your App component, like:

    const [items, setItems] = useState([]);
    
    Login or Signup to reply.
  2. UseEffect doesn’t seem to work on first render of page

    With the information we have it’s difficult to determine what is the issue, but I think the best thing you could do is to move the fetching logic to the Home component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search