简体   繁体   中英

Not able to display data fetched from API in React

I am new to react and am creating a simple application. I can print the data obtained in JSON format from GET method in the console. However I cannot display them in form. Please help me in resolving it.

import React, { useState, useEffect } from "react";
import {ReactComponent as ArrowLeft} from '../assets/arrow-left.svg';
const TaskPage = ({ match,history }) => {
  let taskId = match.params.id;
  let [task, setTask] = useState([]);

  useEffect(() => {
    getTask();
  }, [taskId]);

  let getTask = async () => {
    if (taskId === "new") return;

    let response = await fetch(`/task/task/${taskId}/`);
    let data = await response.json();
    setTask(data);
  };

      let updateNote = async () => {
        fetch(`/api/notes/${taskId}/`, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(task),
        });
      };

      let handleSubmit = () => {
        updateNote()
        history.push('/')
    }

      let handleChange = (value) => {
        setTask((task) => ({ ...task, description: value }));
        console.log(task)
        console.log("Handle Change:", task);
      };

  return (
    <div>
      <h3>
        <ArrowLeft onClick={handleSubmit} />
      </h3>

      <textarea
        onChange={(e) => {
          handleChange(e.target.value);
        }}
        value={task.description}
      ></textarea>
    </div>
  );
};

export default TaskPage;

The browser doesnt show an error for task.description . However I am not able to show it in the textarea field. It appears blank.react

If want to see if any API call happen and what was payload/response - open chrome's developer tools (right click -> inspect on any part of page) and select "Network" tab, look inside for your call, what was payload & response to confirm your API call is actually like you expect it to be. If everything fine there, then look at your JS code. Now there is no clue if API is even working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM