Is there a way to showcase the newly added state object on the page without having to reload the page?

I am currently showcasing the attributes (recipe title, image URL) of items from a state. These items originate from mongodb. Below is my current code flow:

  1. Create an empty array state variable named initialRecipes using
    const [initialRecipes, setRecipes] = useState([]);
  2. Retrieve the recipes from the database and add each object to the state array through
    setRecipes([...initialRecipes, response.data.message[i]])
  3. Display the recipes on the page by utilizing return() and iterating over the initialRecipes variable with the .map function
  4. Add a new recipe to the state variable upon form submission and automatically display the newly added recipe on the page - This is my current challenge

Recipes.js

import React, { useState, useEffect } from 'react';
// code snippet

const Recipes = () => {
  const [formFieldValue, setFormFieldValues] = useState({
    recipe_name: '',
    image_url: '',
    buttonText: 'Submit'
  });
  const {recipe_name, image_url, buttonText} = formFieldValue;
  const [initialRecipes, setRecipes] = useState([]);

  useEffect(() => {
    loadAllRecipes();
  }, []);


  const loadAllRecipes = () => {
    axios({
      method: 'GET',
      url: `${process.env.REACT_APP_API}/recipe`,
    })
    .then(response => {
      for (let i=0; i<response.data.message.length; i++) {

        // save each object to state array
        setRecipes([
          ...initialRecipes,
          response.data.message[i]
        ])
      }
    })
    .catch(error => {
      // code snippet
    });
  };

  // store changes in form inputs to state
  const handleChange = (name) => (event) => {
    setFormFieldValues({...formFieldValue, [name]: event.target.value});
  };


  // form fields snippet
  const addRecipeForm = () => (
    <form>
      <div className="form-group">
        <label className="text-muted">Recipe name</label>
        <input type="text" className="form-control recipe-form-input" value={recipe_name} onChange={handleChange('recipe_name')} />
      </div>

      <div className="form-group">
        <label className="text-muted">Image URL</label>
        <input type="text" className="form-control recipe-form-input" value={image_url} onChange={handleChange('image_url')} />
      </div>

      <div>
        <button className="btn btn-primary btn-submit" onClick={handleSubmit}>Submit</button>
      </div>
    </form>
  );


  // add new recipe through form
  const handleSubmit = event => {
    event.preventDefault();

    axios({
      method: 'POST',
      url: `${process.env.REACT_APP_API}/recipe`
    })
    .then(response => {
      console.log('Recipe saved successfully!', response);
    })
    .catch(error => {
      // console.log(error.response.data.error);
    });
  };

  // display add recipe form and iterate through all recipes
  return (
    <Layout>
      <div className="row">
        {addRecipeForm()}
      </div>

      <div className="row">
        <h2 className="title text-center">List of Recipes</h2>

        <div className="all-recipes-list ">
          {
            initialRecipes.map((recipe, index) => {
                return (
                  <div key={index} className="wrapper">
                    <img className="image" src={recipe.image_url} />
                    <a className="link" href="#">
                      <h4 className="title">{recipe.recipe_name}</h4>
                    </a>
                  </div>
                );
            })
          }
        </div>
    </Layout>
  );
};

export default Recipes;

Issue: How can I display the newly added Recipe via the API(saved in MongoDB) endpoint within the

<div className="all-recipes-list"></div>
element on the page without refreshing?

Any assistance would be greatly appreciated. Thank you!

Answer №1

Following the post request, retrieve the data either through a get request or utilize the react query to fetch the data using the useQuery functionality as per your requirements. Explore react-query here

const submitForm = event => {
    event.preventDefault();

    axios({
      method: 'POST',
      url: `${process.env.REACT_APP_API}/recipe`
    })
    .then(response => {
      console.log('Recipe saved successfully!', response);
      axios({
      method: 'GET',
      url: `${process.env.REACT_APP_API}/recipe`,
     })
     .then(response => {
       for (let i=0; i<response.data.message.length; i++) {

         // Save each object to state array
         setRecipes([
           ...initialRecipes,
           response.data.message[i]
         ])
       }
     })
     .catch(error => {
       // Handle error code
     });
    })
    .catch(error => {
      // console.error(error.response.data.error);
    });
  };

Answer №2

After some troubleshooting, I have successfully resolved the issue at hand. The solution involved inserting

setRecipes([...initialRecipes, newRecipe]);
within the
const handleSubmit = event => ();

  // include new recipe in the form
  const handleSubmit = event => {
    event.preventDefault();

    axios({
      method: 'POST',
      url: `${process.env.REACT_APP_API}/recipe`
    })
    .then(response => {
      let newRecipe = JSON.parse(response.config.data); // convert new recipe from string to object
      console.log('Recipe is saved successfully!', response);

      setRecipes([...initialRecipes, newRecipe]); // append new recipe to the current state
    })
    .catch(error => {
      // console.log(error.response.data.error);
    });
  };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Despite changes in the state they are set to, the InitialValues remain constant

I am facing an issue with a Semantic-UI modal that includes a redux-form as its content. The form is passed to the modal when it opens, and the form element has an initialValues prop mapped to state. <FormModal handl ...

Embed React HTML entities within an input's placeholder text

Is there a way to implement this code in React? <input type="text" placeholder="&#xf124; Location" /> I considered using dangerouslySetInnerHTML, but it doesn't seem suitable for setting props like the placeholder attribute. ...

show the way

Currently, I am utilizing JavaScript within an HTML page to showcase GPS positions with markers that are all interconnected. I have embarked on developing a map and direction application using the Google Maps V3 API. As of now, successfully displayed the ...

Using CSS3 to apply transformations to multiple divs based on their individual attributes

I am currently developing JavaScript code that will enable the use of HTML like the example below: <div class="box" data-vert-speed="7">ContentDiv1</div> <div class="box" data-hori-speed="10">ContentDiv2</div> <di ...

Ensuring Form Integrity through jQuery Validation

I am struggling to customize the errorClass and validClass using JQuery validation. I believe that by adding the .validate function and setting the parameters, it should work. However, even though the validation message displays correctly, the classes re ...

Hiding a div using swipe gestures in Angular

What am I trying to achieve? I aim to hide a div when swiped right. This specific action will close the pop-up that appears after clicking a button. What tools are at my disposal? I am utilizing Ionic framework for this task. Within my app.js, I have i ...

Why does executing an executable from a Node.js application on Heroku yield a "Permission Denied" error, while running it from the bash shell works fine?

We are working with a nodejs application deployed on Heroku. In our code, we have the following snippet: var spawn = require('child_process').spawn; var child = spawn('/bin/bash', ['-c', '/app/node_modules/wkhtmltopdf-pr ...

I am looking to modify the background color of the columns in an Ant Design table based on whether the index of my data is even or odd

I am trying to change the background color of the columns in an Ant Design table based on the index of my data being even. Can anyone provide suggestions on how to achieve this? I have my data in a list and I want to set a condition through a loop to cha ...

Guide on utilizing the latest insertCSS and removeCSS features in manifest version 3

Need help with using the new insertCSS and removeCSS in manifest v3. The documentation is not very clear and lacks examples. I have a CSS file that I need to inject into a page and then remove it. The code looks something like this: background.js documen ...

Is it possible to assign binary content to the src attribute of an img, audio, or video tag?

Picture this scenario: I send an ajax request to my PHP server with the name of an image file, and the server is restricted from sending a direct link to the file. Instead, it must send the file contents using PHP's readfile(); function. Now, when thi ...

I'm encountering an issue with the React state where it seems to be endlessly nesting

I am new to React and I seem to be encountering an issue where every time I trigger a click event, the state object continues to nest. The code snippet below is part of the App component. const [state, setstate] = useState('') useEffect(() =& ...

Troubleshooting problems with installing Bower on El Capitan

I have provided a detailed explanation to ensure the best possible solution for my issue. System Information: - MacOS version 10.11.6 El Capitan - Homebrew installed with Node, npm, and git via Homebrew - Xcode and command line tools are also installed $ ...

Trigger an Ajax function using a button within a Bootstrap modal

I need to trigger an ajax function after selecting an option from a bootstrap confirmation modal. The modal will appear by calling the remove(parameter) function. Any assistance would be greatly appreciated function remove(parameter){ // $("#remove-mod ...

Sending data to a PHP page to maintain state in an Angular application

Here is my current setup: In a dynamic Angular environment, I have various states connected to PHP pages. These PHP pages rely on specific data variables, typically provided as GET parameters outside of Angular. Now, I am looking for a way to switch to a ...

How come only the individual top, bottom, left and right paddings function correctly while the combined padding does not respond?

Seeking to customize a button using SCSS file that is connected to HTML. This button is part of a flex layout design. The element's size is set at 83.333×16px. The box-sizing property is defined as: box-sizing: border-box; Adding padding with s ...

CSS Padding Hover Transition solution for Eliminating Flickering Text issue

Is it possible to achieve this? I'm attempting to animate the padding around a centered text link. When the text link is clicked, the padding changes from 20% to 100%, which works correctly. The text is horizontally and vertically centered using CSS ...

Incorporating React Bootstrap into a component for stylish card designs

It would be great if the cards could be displayed in rows of 4 on the page. However, I encountered an error: An error occurred during compilation of MyDishes.js file. The error message reads: SyntaxError: /Users/adiskop/zestie-frontend/src/components/MyDi ...

Encountering an Uncaught TypeError that is hindering an alert for the score, but I am uncertain about the solution despite the game functioning properly

My Yahtzee code is functioning normally during gameplay, but I'm facing issues with getting alerts for the total score and bonus points. I have identified where the problem lies but I am unsure how to resolve it. I attempted debugging through alerts, ...

Handling invalid JSON strings in controller functions with JavaScript and Node.js

Issue with Incorrect JSON Formatting in Node.js Controller Function Upon sending a JSON object via AJAX to a route in Node.js, the req.body data received in the controller function seems to be incorrectly formatted. What could be causing this issue? Java ...

Can you iterate through two arrays to find common values?

Upon examining my firebase database, I found the following structure: Users { askdfasdf: John: { Selection: [1,2,3] }, fasfadffe: Mark: { Selection: [1,2,4] } } Players { { name: &apos ...