0

My array of API generated "todo" objects.

That is console logged, but i have also saved it as a variable, todosData. Now this variable used to be the same format( array of objects with id, title, completed ) but my hardcoded data. I rendered this with components as my app is made with react. This is the code for it:

import React from "react";
import TodoItem from "./TodoItem";
import todosData from "./TodosData";

// Container for every todo object

export default function Todos() {
  const todoItemArray = todosData.map((todo) => {
    return <TodoItem title={todo.title} key={todo.id} completed={todo.completed} />;
  });
  return <div>{todoItemArray}</div>;
}

Now as you can see i havent even changed the array name when i switched from hardcoded data to api data. Both were an array of objects, as i mentioned. Just this map method is rendered 0 components to my website. Before it rendered all ( when i hardcoded the values ). Im completely confused.

This is the fetch() method to get the data. Even though my console.log shows that isnt the problem:

let todosData = [];

fetch("https://jsonplaceholder.typicode.com/posts/")
  .then((res) => res.json())
  .then((data) => todosData.push(...data))
  .then(() => console.log(todosData));

export default todosData;

1 Answer 1

1

You can't just store your data in a variable. React does not know when you mutate it. You need to use component state so that react knows when to re-render your component. Also the place to fetch data is in an effect:

export default function Todos() {
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/")
      .then(res => res.json())
      .then(data => setTodos(data))
  }, []);

  return (
    <div>
      {todos.map(todo => (
        <TodoItem title={todo.title} key={todo.id} completed={todo.completed} />
      )}
    </div>;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Seems like i jumped the gun and thought i could just add an api. I havent gotten confident with states yet and the tutorial im using hasnt gone into them yet... okay thanks for letting me know!
@LeonMichalak Yeah, react state is one of the most important basic concepts. You will for sure need it if you want to do anything interactive or async in react.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.