Getting this Warning message in my browser console

Viewed 20

Error: You should call navigate() in a React.useEffect(), not when your component is first rendered. I am getting this warning in my browser console every time as I am new to react I am not getting how to remove that warning message if any one can help I am thankful to them.

PaymentScreen.js :

import React, { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { savePaymentMethod } from '../actions/cartActions';
import CheckoutSteps from '../components/CheckoutSteps'

export default function PaymentScreen(props) {

    const history = useNavigate();
    const cart = useSelector((state) => state.cart);
    const {shippingAddress} = cart;
    if(!shippingAddress.address){
        history('/shipping');//getting console message for this line
    }

    const [paymentMethod, setPaymentMethod] = useState('Paypal');

    const dispatch = useDispatch();

    const submitHandler = (e)=>{
        e.preventDefault();
        dispatch(savePaymentMethod(paymentMethod));
        history('/placeorder');
    }
  return (
    <div>
        <CheckoutSteps step1 step2 step3></CheckoutSteps>
        <form className='form' onSubmit={submitHandler}>
            <div>
                <h1>Payment Method</h1>
            </div>
            <div>
                <div>
                    <input type="radio" id="paypal" value="PayPal" name ="paymentMethod" required checked onChange={(e)=> setPaymentMethod(e.target.value)}></input>
                    <label htmlFor='paypal'>PayPal</label>
                </div>
            </div>
            <div>
                <div>
                    <input type="radio" id="stripe" value="Stripe" name ="paymentMethod" required onChange={(e)=> setPaymentMethod(e.target.value)}></input>
                    <label htmlFor='stripe'>Stripe</label>
                </div>
            </div>
            <div>
                <button className='primary' type='submit'>Continue</button>
            </div>
        </form>
    </div>
  )
}

CartAction.js:

import Axios from "axios";
import { CART_ADD_ITEM, CART_REMOVE_ITEM, CART_SAVE_PAYMENT_METHOD, CART_SAVE_SHIPPING_ADDRESS } from "../constants/cartConstants";

export const addToCart = (productId,qty)=> async( dispatch, getState)=>{
    const {data} = await Axios.get(`/api/products/${productId}`);

    dispatch({
        type: CART_ADD_ITEM,
        payload: {
            name: data.name,
            image: data.image,
            price: data.price,
            countInStock: data.countInStock,
            product: data._id,
            qty,
        }
    });
    localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems));
};


export const removeFromCart = (productId) => (dispatch,getstate) =>{
    dispatch({type : CART_REMOVE_ITEM, payload: productId});
    localStorage.setItem('cartItems', JSON.stringify(getstate().cart.cartItems))
}

export const saveShippingAddress=(data)=>(dispatch)=>{
    dispatch({type: CART_SAVE_SHIPPING_ADDRESS, payload : data});
    localStorage.setItem('shippingAddress',JSON.stringify(data));
}

export const savePaymentMethod=(data)=>(dispatch)=>{
    dispatch( {type : CART_SAVE_PAYMENT_METHOD, payload:data});
}
1 Answers

Warning is correct you should keep it in useEffect hook to avoid executing it every time, here in useEffect it will execute once on load

import React, { useState, useEffect } from 'react'
...
...

useEffect(()=>{
      if(!shippingAddress && shippingAddress.address){
        history('/shipping');//getting console message for this line
      }
    },[])
Related