Matt Schubert
Matt Schubert

Reputation: 1003

React use state hook not updating

I am loading data on the initial load. When they user clicks the button to add a recognition, the api call adds it, and returns it. I add the new post to the array, but the new update doesn't render. The return object, and the array of objects are the same object type. When I reload the page, the new post is rendered, just not on the add function. Is there something that I am missing?

  const [recognitions, setRecognitions] = useState([]);

useEffect(() => {
    Api.GetRecognitions(params)
      .then(response => {
        const items = response || [];
        setRecognitions(recognitions => [...recognitions, ...items]);
      })
  }, [setRecognitions]);

const handleAddPost = () => {
    Api.AddRecognition(params)
    .then(response => {
      const newPost = response;
      setRecognitions(recognitions=> [...recognitions, newPost])
    });
  }

<Form.Group>
      <Form.Field>
        <Button basic color='blue' onClick={handleAddPost}>Add</Button>
      </Form.Field>
    </Form.Group>
    <Form.Group>
      <Form.Field>
      {recognitions.map(recognition => (
        <RecogWallPost 
          key={recognition.recogStagingId}
          recognition={recognition}
          participantId={participantId}
        />
      )
      )}
      </Form.Field>
    </Form.Group>

Upvotes: 0

Views: 54

Answers (2)

larz
larz

Reputation: 5766

Instead of passing [setRecognitions] as the second argument to useEffect, you want to pass [recognitions]. This tells the useEffect hook to run every time recognitions changes, which it does inside handleAddPost.

Upvotes: 2

Simon
Simon

Reputation: 6462

You have to create an async function, and then use it as follow:

useEffect(() => {
  async function initData() { 
    Api.GetRecognitions(params)
      .then(response => {
        const items = response || [];
        setRecognitions(recognitions => [...recognitions, ...items]);
      })
  }
  initData()
}, [setRecognitions]);

Upvotes: 0

Related Questions