0
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 object1 and React ignores the empty array set as initial value.

Jasperan
  • 2,154
  • 1
  • 16
  • 40
Mentor_Aliu
  • 11
  • 1
  • 4
  • it replaces the state, you have to build a new array when setting the state. – Emile Bergeron Nov 20 '21 at 16:47
  • 1
    On the first render, it will be an empty array. When you call setRelatedPosts(object1), it will rerender with just that object as the state (the array is gone) – Nicholas Tower Nov 20 '21 at 16:47
  • Does this answer your question? [Push method in React Hooks (useState)?](https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate) – Emile Bergeron Nov 20 '21 at 16:47

3 Answers3

1

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 ([])

Farrukh Ayaz
  • 310
  • 3
  • 15
0

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

Shivam Jha
  • 3,160
  • 3
  • 22
  • 36
0

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]);
  • Hi thank you for answering, my question was I meant does relatedPosts become relatedPosts=[ object1 ] or relatedPosts=object1 Basically does object1 get pushed to the initial empty array or the initial empty array gets removed and it becomes just object1 – Mentor_Aliu Nov 20 '21 at 17:50