Home > database >  Displaying fetched data from API
Displaying fetched data from API

Time:11-17

enter image description here

function App() {
  const [todos, setTodos] = useState(null);

  useEffect(() => {
    const GetTodos = async () => {
      try {
        const { data } = await axios.get("api/orders");
        console.log(data);
        setTodos(data);
        console.log(todos);
      } catch (err) {
        console.log(err);
      }
    };
    GetTodos();
  }, []);

  return (
    <div className="App">
      <h1>hello</h1>
      {todos?.map((todo) => (
        <p key={todo.ID}>{todo.ID}</p>
      ))}
    </div>
  );
}

How can I make the data I got from the API display on the page, I can see that it works when I log it to the console but it doesn't show up on the page

enter image description here

CodePudding user response:

Okay the problem is your data returns an Array of Arrays. Because your data has just one array nested inside, we can just use it as the data hook, something like this:

setTodos(data[0]);

to understand, here is an example enter image description here

CodePudding user response:

Try doing so :

function App() {
  const [todos, setTodos] = useState(null);

  useEffect(() => {
    const GetTodos = async () => {
      try {
        const { data } = await axios.get("api/orders");
        console.log(data);
        setTodos(data[0]);
      } catch (err) {
        console.log(err);
      }
    };
    GetTodos();
  }, []);

  return (
    <div className="App">
      <h1>hello</h1>
      {todos && todos.map((todo) => (
        <p key={todo.ID}>{todo.ID}</p>
      ))}
    </div>
  );
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related