简体   繁体   中英

How can update my useState variable if I'm already using useEffeck hook?

I'm working in a personal project to learn more about the way react hooks works. Recently I posted a question where I was using a variable inside an axios call and in the moment when I tried to update it (setVariable), it didn't worked. The answer I learn that useState make asynchonous calls so my variable didn't update so I can use useEffect to solve that.

But now I'm doing another axios call and I'm already using my useEffect hook in that component so I think it can't be used twice. Can you please explain me what can I do in those cases?

Here is the component that I'm working with:

type modalBodyFormProps = {
handleSubmit: any,
objectS: any

}

const ModalBodyUpdatePreparacion: React.FC = (props: modalBodyFormProps) => {

const[stockPreparaciones, setStockPreparaciones] = useState<any[]>([]);
const[ingsPreparaciones, setIngsPreparaciones] = useState<any[]>([]);

useEffect(() => {
    getPreparaciones();
    getIngredientePrep();
},[stockPreparaciones.length]);

const getPreparaciones = () => {
    console.log(props.objectS);
    axios.get('https://inventario-services.herokuapp.com/invservice/stock/getone/?codigo=' + props.objectS)
    .then(result => {
        console.log(result);
        setStockPreparaciones(result.data.preparaciones); //Here is where I need to use useEffect hook so this value can be updated
        console.log(stockPreparaciones);
    }).catch(console.log); 
}

const getIngredientePrep = () => {
    stockPreparaciones.map(st => {
        axios.get('https://inventario-services.herokuapp.com/invservice/stock/getone/?codigo=' + st.codigo_preparacion)
        .then(result => {
            console.log(result);
            setIngsPreparaciones([...ingsPreparaciones, result.data]); //I want to update this value, however it appears as empty.
            console.log(ingsPreparaciones);
        });
    });
}

return(
    <div>

    </div>
);}

Thank you for your help

You can use the hook useEffect the times you want. The only thing you must be aware is about the dependency array and be careful about combinations. You can even do this.

useEffect(()=> {
  doSomethingWithFoo();
}, [foo]);

useEffect(()=> {
  doSomethingWithBar();
}, [bar]);

useEffect(()=> {
  doSomethingWithFooOrBar();
}, [foo, bar]);

Separate effects as per need. Also, make use of async-await pattern.

Like so:

const { objectS } = props;

useEffect(
  async () => {
    const result = await axios.get(`heroku_url/?codigo=${objectS}`);
    setStockPreparaciones(result.data.preparaciones);    
  }
  , [objectS]
);

// watcher for state updates
useEffect(
  () => {
    console.log(stockPreparaciones)
  }
  , [stockPreparaciones]
) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM