Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

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

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;
question from:https://stackoverflow.com/questions/65847482/combine-two-objects-in-react-no-success-so-far

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...