Home > front end >  React initial state as empty array question?
React initial state as empty array question?

Time:11-21

const object1 = {name: "David", id=5};

If I use the initial state as an empty array:

const [relatedPosts, setRelatedPosts] = useState([])

and then I use setRelatedPosts(object1) will the relatedPosts become an array with object1 inside it? or it will be just the object1 and React ignores the empty array set as initial value

CodePudding user response:

For what I have understood that you are asking if the data type for the state will remain array or not!? Well the answer is that relatedPost will be set to as an object if set to relatedPosts=object1 not relatedPosts=[object1]

react will ignore the initial value ([])

CodePudding user response:

If you declared:

const [relatedPosts, setRelatedPosts] = useState([]) & then do setRelatedPosts(object1), then the value of variable relatedPosts becomes object1: it is that simple.

See declaring a state variable

CodePudding user response:

Please describe the question. What you actually need.

I guess your problem and try to solve.

  const [relatedPosts, setRelatedPosts] = useState([]);

  const object1 = {name: "David", id:5}; //{name: "David", id=5} use ':' instead '=' when in object

  setRelatedPosts([object1, ...relatedPosts]);
  • Related