0

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?

1
  • 2
    .push() has always mutated the array returned the new length of the array. Commented Aug 6, 2021 at 13:25

1 Answer 1

1

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]);
Sign up to request clarification or add additional context in comments.

3 Comments

Where as x is equal to the previous state.
@AntonBahurinsky Maybe i'm doing something wrong but for me thats completely overwriting the original array with the new one?
@snwmn technically yes, but it is a good practice to overwrite arrays and objects rather than mutating them. Check out what React docs say: reactjs.org/docs/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.