最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Combine two objects in react, no success so far - Stack Overflow

programmeradmin1浏览0评论

I'm trying to bine 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 #2:

After bining the objects and logging the bined result I only get Object #1 like this:

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 bine 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 bine the two objects, no success
      console.log("3. Combined object - Only gets Object #1...", stockObject)
    }, 2000);

    setOpen(true);
  };
 
}

export default PortfolioComponent;

I'm trying to bine 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 #2:

After bining the objects and logging the bined result I only get Object #1 like this:

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 bine 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 bine the two objects, no success
      console.log("3. Combined object - Only gets Object #1...", stockObject)
    }, 2000);

    setOpen(true);
  };
 
}

export default PortfolioComponent;
Share Improve this question asked Jan 22, 2021 at 14:57 gospeid12gospeid12 1,0123 gold badges14 silver badges27 bronze badges 6
  • Do you get the same results if you log {...findClickedStock, ...stockData} directly? – Ted Brownlow Commented Jan 22, 2021 at 15:02
  • Does this answer your question? useState set method not reflecting change immediately – Hamza El Aoutar Commented Jan 22, 2021 at 15:06
  • you dont need to use setTimeout for waiting api result. Just return a promise from getStock and it in handler like getStock().then(res => {...}); – poltorin Commented Jan 22, 2021 at 15:18
  • @poltorin I know I can do that but cant figure out how really, so this is a fast resulotion :p Can you show me how i can proceed? – gospeid12 Commented Jan 22, 2021 at 15:27
  • @gospeid12 added an answer below – poltorin Commented Jan 22, 2021 at 15:31
 |  Show 1 more ment

2 Answers 2

Reset to default 2

From the Hooks API Reference:

Note Unlike the setState method found in class ponents, useState does not automatically merge update objects. You can replicate this behavior by bining 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 remended for managing state with multiple sub-values.

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 bine 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);
};
发布评论

评论列表(0)

  1. 暂无评论