Home > Net >  How to post React form data to a (LOCAL)db.json file using axios?
How to post React form data to a (LOCAL)db.json file using axios?

Time:07-02

I am struggling to understand how to post the data entered into my form to my JSON file on my localhost. The HTML form takes a name, title, and content. The goal is to use the form to create a new article, post that HTML form data to the JSON file, and pull then pull the data and display it on the webpage.

This is the JSON file:

{
"posts": [
{
  "name": "learn-react",
  "title": "The Fastest Way to Learn React",
  "content": [
      "Welcome! Today we're going to be talking about the fastest way to",
      "learn React. We'll be discussing some topics such as proin congue",
      "ligula id risus posuere, vel eleifend ex egestas.Sed in turpis leo.",
      "Aliquam malesuada in massa tincidunt egestas.Nam consectetur varius turpis,",
      "non porta arcu porttitor non.In tincidunt vulputate nulla quis egestas.Ut",
      "eleifend ut ipsum non fringilla.Praesent imperdiet nulla nec est luctus, at",
      "sodales purus euismod.",
      "Donec vel mauris lectus.Etiam nec lectus urna.Sed sodales ultrices dapibus.",
      "Nam blandit tristique risus, eget accumsan nisl interdum eu.Aenean ac accumsan",
      "nisi.Nunc vel pulvinar diam.Nam eleifend egestas viverra.Donec finibus lectus",
      "sed lorem ultricies, eget ornare leo luctus.Morbi vehicula, nulla eu tempor",
      "interdum, nibh elit congue tellus, ac vulputate urna lorem nec nisi.Morbi id",
      " consequat quam.Vivamus accumsan dui in facilisis aliquet.",
      "Etiam nec lectus urna.Sed sodales ultrices dapibus.",
      "Nam blandit tristique risus, eget accumsan nisl interdum eu.Aenean ac accumsan",
      "nisi.Nunc vel pulvinar diam.Nam eleifend egestas viverra.Donec finibus lectus",
      "sed lorem ultricies, eget ornare leo luctus.Morbi vehicula, nulla eu tempor",
      "interdum, nibh elit congue tellus, ac vulputate urna lorem nec nisi.Morbi id",
      "consequat quam.Vivamus accumsan dui in facilisis aliquet."
  ]
},{
"name": "learn-node",
"title": "How to Build a Node Server in 10 Minutes",
"content": [
    "In this article, we 're going to be talking looking at a very quick way",
    "to set up a Node.js server.We 'll be discussing some topics such as proin congue",
    "ligula id risus posuere, vel eleifend ex egestas.Sed in turpis leo.",
    "Aliquam malesuada in massa tincidunt egestas.Nam consectetur varius turpis,",
    "non porta arcu porttitor non.In tincidunt vulputate nulla quis egestas.Ut",
    "eleifend ut ipsum non fringilla.Praesent imperdiet nulla nec est luctus, at",
    "sodales purus euismod.",
    "Donec vel mauris lectus.Etiam nec lectus urna.Sed sodales ultrices dapibus.",
    "Nam blandit tristique risus, eget accumsan nisl interdum eu.Aenean ac accumsan",
    "nisi.Nunc vel pulvinar diam.Nam eleifend egestas viverra.Donec finibus lectus",
    "sed lorem ultricies, eget ornare leo luctus.Morbi vehicula, nulla eu tempor",
    "interdum, nibh elit congue tellus, ac vulputate urna lorem nec nisi.Morbi id",
    "consequat quam.Vivamus accumsan dui in facilisis aliquet.",
    "Etiam nec lectus urna.Sed sodales ultrices dapibus.",
    "Nam blandit tristique risus, eget accumsan nisl interdum eu.Aenean ac accumsan",
    "nisi.Nunc vel pulvinar diam.Nam eleifend egestas viverra.Donec finibus lectus",
    "sed lorem ultricies, eget ornare leo luctus.Morbi vehicula, nulla eu tempor",
    "interdum, nibh elit congue tellus, ac vulputate urna lorem nec nisi.Morbi id",
    "consequat quam.Vivamus accumsan dui in facilisis aliquet."

]
},{
 "name": "my-thoughts-on-resumes",
 "title": "My Thoughts on Resumes",
 "content": [
  "Today is the day I talk about something which scares most people: resumes.",
  " In reality, I 'm not sure why people have such a hard time with proin congue,",
  " ligula id risus posuere, vel eleifend ex egestas.Sed in turpis leo.",
  " Aliquam malesuada in massa tincidunt egestas.Nam consectetur varius turpis,",
  " non porta arcu porttitor non.In tincidunt vulputate nulla quis egestas.Ut",
  " eleifend ut ipsum non fringilla.Praesent imperdiet nulla nec est luctus, at",
  " sodales purus euismod.",
  "Donec vel mauris lectus.Etiam nec lectus urna.Sed sodales ultrices dapibus.",
  "Nam blandit tristique risus, eget accumsan nisl interdum eu.Aenean ac accumsan",
  "nisi.Nunc vel pulvinar diam.Nam eleifend egestas viverra.Donec finibus lectus,",
  "sed lorem ultricies, eget ornare leo luctus.Morbi vehicula, nulla eu tempor",
  "interdum, nibh elit congue tellus, ac vulputate urna lorem nec nisi.Morbi id",
  "consequat quam.Vivamus accumsan dui in facilisis aliquet.",
  "Etiam nec lectus urna.Sed sodales ultrices dapibus.",
  "Nam blandit tristique risus, eget accumsan nisl interdum eu.Aenean ac accumsan",
  "nisi.Nunc vel pulvinar diam.Nam eleifend egestas viverra.Donec finibus lectus",
  "sed lorem ultricies, eget ornare leo luctus.Morbi vehicula, nulla eu tempor",
  "interdum, nibh elit congue tellus, ac vulputate urna lorem nec nisi.Morbi id",
  "consequat quam.Vivamus accumsan dui in facilisis aliquet."
 ]
 }
 ],
"comments": [
 {
  "id": 1,
  "body": "some comment",
  "postId": 1
}
],
"profile": {
"name": "typicode"
}
}

And this is the react code

import React,{ useState } from "react"
import axios from "axios";

const ArticleNew = ()=>{
const [formData, setFormData] = useState({
    name: '',
    title: '',
    content: ''
});

function handleChange(e){
    const {name, value} = e.target
    setFormData(prevFromData =>{
        return{
            ...prevFromData,
            [name]: value
        }
    })
}

const handleSubmit = async () =>{
const api = axios.create({
    baseURL: 'http://localhost:8080/posts'
   })
let res = await api.post('/', ({
    name: JSON.stringify(""),
    title: JSON.stringify(""),
    content: JSON.stringify(""),
    Headers:{
        "Content-Type": "application/json; charset=UTF-8"
    }
})).then(console.log(res)).catch(console.error())
console.log(res)
}
return(
    <>
        <form>
            <input type="text" 
                className="input"
                placeholder="Article Name" 
                name="name" 
                value={formData.name}
                onChange={handleChange}
            /><br></br>
            <input type="text" 
                className="input"
                placeholder="Title" 
                name="title" 
                value={formData.title}
                onChange={handleChange}
            />           
            <textarea 
                placeholder="Type article content"
                name="content"
                value={formData.content}
                onChange={handleChange}
            />
            <button onClick={handleSubmit}>Post</button>
        </form>
    </>
)
}

export default ArticleNew;

CodePudding user response:

For storing the data in a JSON file, you would need to have backend server which can be any language like Node.js, PHP, As you cannot access the Filesystem in the browser.

For the React Part, you can do it in the following way

import React,{ useState } from "react"
import axios from "axios";      
const api = axios.create({
            baseURL: 'http://localhost:8080'
 }) // Create api variable outside the ArticleNew component so it can be reused
    
    
     const handleSubmit = async () => {
       try {
           
        let res = await api.post('/posts', formData, {
        headers: {
            'Content-Type': 'application/json',
        }
    }) // we can directly pass formData object axios will transform into json,
            
        console.log(res)
       } catch(e) {
         console.error(e)
       }
    
     }

CodePudding user response:

You can use the following code : This function is general handler for your inputs, as long as each input element have the same value of name as your object properties

 const handleChanges = ({ currentTarget }) => {
    const info = { ...data };
    info[currentTarget.name] = currentTarget.value;
    setData(info);
  };

You must use this function to handle the onChange event. Then you can call axios.post inside your handleSubmit like this :

const {data: post} = await axios.post(YourUrl, data}

Then you can use your post result, for example to push it in a posts state that will update your UI.

  • Related