Flamiga
Flamiga

Reputation: 1

How to post data into my React application?

I have an issue with my react, I'm working on a MERN template but I can't make my post to work, and I want to be able to add a new blog on my site. When I add a new blog, I seem to get it in my console.log. (the title and the description) but not on my app, I believe it's something with my fetch.

this is my app.js file

import React, {useEffect, useState} from 'react';
import {Router} from "@reach/router";
import Blogs from "./Blogs";
import Blog from "./Blog"; 

const API_URL = process.env.REACT_APP_API;

function App() {
  const [blog, setBlogs] = useState([]);
  const [postCount, setPostCount] = useState(0);


  
  useEffect(() => {
    async function getData() {
      const url = `${API_URL}/blogs`;
      const response = await fetch(url);
      const data = await response.json();
      setBlogs(data);
    }
    getData();
  }, [postCount]); 

  function getBlog(id) {
    const blogObject = blog.find(data => data._id === id);
    return blogObject;
  }


  //callback så min addBlog ved hvor den skal hente data fra
  async function addBlog(title, description, date) {
    console.log("title", title);
    console.log("Description" , description);

    const newBlog = {
      title: title,
      description: description,
      date: date
    }   

    const url = `${API_URL}/blogs`;
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json'
     },
      body: JSON.stringify(newBlog),
    });
    const data = await response.json();
    //setBlogs([...blogs, newBlog]);
    setPostCount(postCount + 1); //call my post count that fecths my data automatic 
    console.log("blog", data);
  }
  
  return (
    <>
      <h1>Blog App!</h1>
     <Router>
       <Blogs path="/" blogs={blog} addBlog={addBlog}>{blog.id}</Blogs>
       <Blog path="/blogs/:id" getBlog={getBlog}></Blog>
     </Router>
    
    </>
  );
}

export default App;

this is my addBlog.js

import React, { useState } from 'react';

function AddBlog(props) {
    //state const for hver properties i din object(question)
    const [title, setTitle] = useState("");
    const [description, setDescription] = useState("");
    const [date, setDate] = useState("");

  

    return (
        <><label>Title: </label>
            <input type="text" placeholder="Write the title of your Blog" size="30" onChange={(event) => {
                setTitle(event.target.value)
            }
            } /><br /><label>Description: </label>
            <input type="text" placeholder="Write the description..." size="30" onChange={(event) => {
                setDescription(event.target.value)
            }} />
           
            <br />
            <button onClick={(event) => props.addBlog(title, description, date)}>Add Question</button>
  

        </>
    );

}

export default AddBlog;

I hope someone is able to help me out.

UPDATE here's my screendump of my console - when I press add blog it says POST 401 unAuthrorized.

SORRY IT WAS THE WRONG PROJECT I POSTED AN IMAGE BUT NOW IT'S THE RIGHT PROJECT

Screendump of my console

Upvotes: 0

Views: 179

Answers (1)

Mantas Astra
Mantas Astra

Reputation: 1062

After looking at your logs, I think you need to send authorization headers alongside your fetch request in order for the back-end to respond.

You could add the authorization header like that - however, you need to find out/generate authorization token that your backend can accept. Also a little improvement, I would make the function a bit more dynamic by allowing it to accept an URL.

   useEffect(() => {
    async function getData(url) {
      const response = await fetch(URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': <your auth token>
        }
      });
      const data = await response.json();
      setBlogs(data);
    }
    getData(`${API_URL}/blogs`);
  }, [postCount]); 

Upvotes: 1

Related Questions