songa
songa

Reputation: 13

conditional rendering with toast and usestate does not work with react

I have my state and I want to display the component if the value is true but in the console I receive the error message Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state my code

import React, { useState} from "react";
import { useToasts } from "react-toast-notifications";

const Index = () => {

  const [test, setTest]= useState(true);
  const { addToast } = useToasts();

  function RenderToast() {

    return (
      <div>
        { addToast('message') }
      </div>
    )}

    return (
      <div>
        {test &&  <RenderToast /> }
      </div>
    )

  

}

Upvotes: 0

Views: 1841

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187004

You cannot set state during a render. And I'm guessing that addToast internally sets some state.

And looking at the docs for that library, you don't explicitly render the toasts. You just call addToast and then the <ToastProvider/> farther up in the tree shows them.

So to make this simple example works where a toast is shown on mount, you should use an effect to add the toast after the first render, and make sure your component is wrapped by <ToastProvider>

const Index = () => {
  const { addToast } = useToasts();

  useEffect(() => {
    addToast('message')
  }, [])

  return <>Some Content here</>
}

// Example app that includes the toast provider
const MyApp = () => {
  <ToastProvider>
    <Index />
  </ToastProvider>
}

how i can display the toast based on a variable for exemple display toast after receive error on backend?

You simply call addToast where you are handling your server communication.

For example:

const Index = () => {
  const { addToast } = useToasts();

  useEffect(() => {
    fetchDataFromApi()
      .then(data => ...)
      .catch(error => addToast(`error: ${error}`))
  }, [])

  //...
}

Upvotes: 1

Related Questions