How to populate the state after an action call in useEffect?

Viewed 68

I am trying to populate the state after calling an action which retrieves the data of an single object. I want to store this data in the state directly.

useEffect(() => {
        getProduct(id);
    }, [getProduct]);

const [formData, setFormData] = useState({});

I tried to store like this:

const ProductEdit = ({getProduct, updateProduct, id, products}) => {
    useEffect(() => {
        getProduct(id);
    }, [getProduct]);

    const [formData, setFormData] = useState({
        name: '',
        quantity: '',
        price: '',
        description: '',
        category: '',
        isImportant: ''
    });

    const {name, quantity, price, description} = formData;

    products.product && setFormData(products.product);
1 Answers

You need to use useEffect hook to set the state variable

const ProductEdit = ({getProduct, updateProduct, id, products}) => {
    useEffect(() => {
        getProduct(id);
    }, [getProduct]);

    const [formData, setFormData] = useState({
        name: '',
        quantity: '',
        price: '',
        description: '',
        category: '',
        isImportant: ''
    });

    const {name, quantity, price, description} = formData;
    
    // This hook will only trigger when `products` will change
    useEffect(() => {
      products.product && setFormData(products.product);
    }, [products]);
    
    
}

Related