Ad

React: Page Not Redirected And Getting Warning: State Updates From The UseState() And UseReducer() Hooks Don't Support The Second Callback Argument

- 1 answer

Goal: I want to get stripe charged, an email sent, cart in local storage cleared, then a message is shown to the user that is successful, then redirect to home page. Everything works fine, until the last step. After the success message is shown, it's not redirected.

Error:

Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().

System:

  • Node.js version: 12.13.0
  • NPM version: 6.12.0
  • Strapi version: 3.0.0-beta.17.4
  • Database: MongoDB atlas cloud
  • Operating system: LinuxMint 19.2 Cinnamon
  • Front-end : React 16.11.0
  • strapi-provider-email-sendgrid": "^3.0.0-beta.17.5"

Code:

const [cartItems,setCartItems] = useState([])

    useEffect(()=> {
        const items = getCart()
        setCartItems(items)
    }, [])


    const showToast = (toastMsg, redirect = false) => {
        setFormData({...formData, toast: true, toastMsg})
        setTimeout(() => setFormData({...formData, toast: false, toastMsg:''},
        // if true passed to 'redirect' argument, redirect home
         ()=> redirect && props.history.push('/')), 
        5000)
    }

const handleSubmitOrder = async () => {
        const amount = calculateAmount(cartItems)
        setFormData({...formData, orderProcessing: true})

        let token
        try {
            //create stripe token
            //create order with strapi (request to backend)
            //set orderProcessing to false set modal to false
            //clear user cart 
            //show success toast 
            let jwtToken = getToken()
            // console.log(jwtToken)
            const response = await props.stripe.createToken()
            token = response.token.id
            // console.log(token)
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer '+ jwtToken
              }
            await axios
            .post(`${apiUrl}/orders`, {
                amount, 
                productItems: cartItems,
                city,
                zipcode, 
                address,
                token
            }, {headers})
            await axios
            .post(`${apiUrl}/email`, {
                    to: confirmEmail,
                    from: '[email protected]',
                    subject: `Order Confirmation from Annie's Vegan Bakery`,
                    text: 'Your order has been processed.',
                    html: '<h1>Expect your order to arrive in 2-3 shipping days.</h1>'
                }
            ,{headers})
            setFormData({...formData, orderProcessing: false, modal: false})
            clearCart()
            showToast('Your order has been successfully submitted', true)
        } catch (error) {
            //set order processing to false, modal to false
            //show error message in toast
            setFormData({...formData, orderProcessing: false, modal: false})
            showToast(error.message)
        }
    }

Question: what is causing this problem and how can I fix it?

Ad

Answer

I solved the problem by writing it like this

 const showToast = (toastMsg, redirect = false) => {
        setFormData({...formData, toast: true, toastMsg})
        setTimeout(() => setFormData({...formData, toast: false, toastMsg:''}), 5000)
        // if true passed to 'redirect' argument, redirect home
        setTimeout(() => redirect &&  props.history.push('/'), 6000)
    }

I am not sure it's the best way but no errors now and everything works well.

Ad
source: stackoverflow.com
Ad