4

I'm trying to combine two object together without any luck... I'm using the spread operator as you should in es6. I'm pretty sure it has something to do with useState. I will start by showing you the console.logs from my objects then the code :)

CONSOLE.LOGS

Object #1:

Object #1

Object #2:

Object #2

After combining the objects and logging the combined result I only get Object #1 like this:

Combined Object

MY CODE

const PortfolioComponent = () => {

const [clickedElement, setClickedElement] = useState({})
const [stockObject, setStockObject] = useState({})
const [stockData, setStockData] = useState({})

const getStock = () => {
    axios.request(stock)
    .then( res => {
      console.log("2. Object #2 from API: ", res.data)
      setStockData(res.data) // HERE I SET THE OBJECT FROM MY API CALL
    })
    .catch( error => {
      console.error(error);
  }

  const handleOpen = name => { // In this function i call the api function and combine the two objects.
    
    let findClickedStock = props.stocksArray.find(item => item.ticker === name)
    setClickedElement(findClickedStock)
    getStock();
    console.log("1. Object #1: ", findClickedStock)

    setTimeout(() => { // Waitning for the api to fetch
      setStockObject({...findClickedStock, ...stockData}) // Here i combine the two objects, no success
      console.log("3. Combined object - Only gets Object #1...", stockObject)
    }, 2000);

    setOpen(true);
  };
 
}

export default PortfolioComponent;
gospecomid12
  • 712
  • 3
  • 11
  • 25

2 Answers2

2

From the Hooks API Reference:

Note Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

Also, check out useReducer which is generally recommended for managing state with multiple sub-values.

notnotparas
  • 177
  • 1
  • 11
1
const getStock = () => {
  return axios.request(stock)
  .then( res => res.data)
  .catch( error => {
    console.error(error);
}

const handleOpen = name => { // In this function i call the api function and combine the two objects.
  
  let findClickedStock = props.stocksArray.find(item => item.ticker === name)
  setClickedElement(findClickedStock)

  console.log("1. Object #1: ", findClickedStock)

  getStock().then((dataFromStockApi) => {
    setStockObject({ ...dataFromStockApi, ...findClickedStock });
  });

  setOpen(true);
};
Dharman
  • 30,962
  • 25
  • 85
  • 135
poltorin
  • 284
  • 1
  • 4
  • 13