Home > Enterprise >  How to POST and GET from mongoDB express server in react hooks?
How to POST and GET from mongoDB express server in react hooks?

Time:10-04

I am getting an error to GET data from my API endpoint. I am able to send data and also update/ delete them from the postTodo()method.

I have added it in a useEffect()so that the I am able to send data to server whenever a Todo is completed or deleted.

But whenever i reload the page, in the devtools, the todos array is [].

Some help would be appreciated.Thanks.

The Todo.jsx

  const postTodo = (todos) => {
    console.log(todos);
    axios.post("http://localhost:4000/api/todos", todos, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      }
    })
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        console.log(err);
      })
  }
  useEffect(() => {
    postTodo(todos) 
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [todos])

  useEffect(() => {
    axios.get("http://localhost:4000/api/todos", {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      }
    })
      .then(res => {
        console.log(res);
        setTodos(res.data.todos)
      })
      .catch(err => {
        console.log(err);
      })
  }, [])

the server.js

const authCheck = (req, res, next) => {
  if (req.headers['authorization']) {
    const token = req.headers['authorization'].split(" ")
    if (token[0] !== 'Bearer') {
      return res.send({ status: 'error', error: 'invalid request' });
    } else {
      req.jwt = jwt.verify(token[1], process.env.jwtSECRET);
      return next();
    }
  }
}

app.post("/api/todos", authCheck, async (req, res) => {
  const todos = req.body
  console.log(todos);
  const { id } = req.jwt
  const user = await User.findByIdAndUpdate(id, { "todos": todos })
  // console.log(user);
})
app.get("/api/todos", authCheck, async (req, res) => {
  const { id } = req.jwt
  const user = await User.findById(id)
  log(user) //user.todos is empty
  res.send({
    status: "ok", todos: user.todos })
})

CodePudding user response:

You can try something like this, where use effect for todos will log the value everytime you create a new todo

const postTodo = (todos) => {
  console.log(todos);
  axios.post("http://localhost:4000/api/todos", todos, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      }
    })
    .then(res => {
      console.log(res);
      getTodos()
    })
    .catch(err => {
      console.log(err);
    })
}

const getTodos = () => {
  axios.get("http://localhost:4000/api/todos", {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      }
    })
    .then(res => {
      console.log(res);
      setTodos(res.data.todos)
    })
    .catch(err => {
      console.log(err);
    })
}

const newTodo = () => {
  const allTodos = [...todos];
  allTodos.push("new Todo at:"   new Date())
  postTodo(allTodos)
}

useEffect(() => {
  console.log('todo-list', todos)
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [todos])

useEffect(() => {
  getTodos()
}, [])

return (<button onClick={() =>  }> Add Todo </button>)

CodePudding user response:

The problem was solved, actually it was the useEffect() issue. I removed the UseEffect and added the postTodos method after every useState hook updation.

  • Related