snwmn
snwmn

Reputation: 3

Pushing to an array is returning index rather then items (React)

I'm trying to add a new object to the end of an array that I'm dynamically fetching over my API. Users complete a form so the data is passed from the form to the state.

The initial first fetch is storing the original array to some react state which is fine, then at some point, a single object should be added to the end of the original array, so the whole array will contain the original data, plus the new object added.

Naturally, I'm trying to use array.push() to try and achieve this, but I keep getting the index rather than the data object.

// declare state will be an array

const [originalPages, setOriginalPages] = useState([]);

// Get all the existing data

loadInitialValues() {
  return fetch(`example.com/api/collections/get/testing_features?token=${process.env.REACT_APP_API_KEY}`)
  .then((res) => {
    return res.json();
  })
  .then((res)=>{
    // set state to be the whole array for this post
    setOriginalPages(res.entries[4].pagebuild);
    return res.entries[4].pagebuild[0].settings;
  })
  .catch((err)=>{
      console.error(err);
  })
}

At this point the data is all working completely fine, the collection of the new data from the forms works fine too. However, this is the point when the data goes to get posted back to update the API but just returns a number:

 onSubmit(formData) {

  // Dynamically hook all the newly collected form data to this new data object

  let theData = {
    component: 'page',
    settings: {
      title: formData.title,
      pageOptions: {
        pageSideImg: formData.pageOptions.pageSideImg,
        isReversed: formData.pageOptions.isReversed,
        paraGap: formData.pageOptions.paraGap,
        paraFont: formData.pageOptions.paraFont,
      },
      pageNavigation: {
        pageSlug: formData.pageNavigation.pageSlug,
        nextPage: formData.pageNavigation.nextPage,
        prevPage: formData.pageNavigation.prevPage,
      },
      globalOptions: {
        projectName: formData.globalOptions.projectName,
        transType: formData.globalOptions.transType,
        menuTrans: formData.globalOptions.menuTrans,
      },
      blocks: formData.blocks
    }
  };
  
  cms.alerts.info('Saving Content...');

   return fetch(`example.com/api/collections/save/testing_features?token=${process.env.REACT_APP_API_KEY}`, {
      method: 'post',
      headers: { 
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
          data: {
                  // Only returning the array count as a number
                  pagebuild: originalPages.push(theData),
                _id: "610963c235316625d1000023"
          }
       })
     })
      .then(response => response.json())
      .catch((err) => {
        cms.alerts.error('Error Saving Content');
        console.log(err);
      });
   },

If anyone has any ideas as to why this is happening id greatly appreciate it!

For reference, I've checked here and maybe I should use spread instead?

Upvotes: 0

Views: 532

Answers (1)

Anton Bahurinsky
Anton Bahurinsky

Reputation: 456

The Array.push doesn't return the final array you would need, but the final length of modified array (that's why you thought it was an index).

Replace this string pagebuild: originalPages.push(theData), with this one:

pagebuild: [...originalPages, theData],

Of course, if you want to update the internal originalPages state value, call this within your onSubmit():

setOriginalPages(x => [...x, theData]);

Upvotes: 1

Related Questions