Home > Net >  How to display POST API data containing string using fetch and map function in React
How to display POST API data containing string using fetch and map function in React

Time:02-21

I am trying to fetch data that i POST in API but it always throws an error "state.map is not a function."

function App() {
  const [state, setState] = useState([]);
  var z = {
    name: "yash",
    subj: "english",
  };

  const requestResp = {
    method: "POST",
    header: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: z,
  };

  fetch(`https://jsonplaceholder.typicode.com/posts`, requestResp)
    .then((response) => response.json())
    .then((data) => setState(data));

  return (
    <div>
      {state.map((todo) => {
        return <pre>{JSON.stringify(todo)}</pre>;
      })}
    </div>
  );
}

I was expecting to see data i posted using POST in output.

CodePudding user response:

Make sure that data variable is returning some data of type array. Because might be possible that in last promise action .then data is not of type array you can check it by following code:

fetch(`https://jsonplaceholder.typicode.com/posts`,requestResp)
.then(response=> response.json())
.then(data=>{console.log(data); setState(data);})

CodePudding user response:

const [Loading, setLoading] = useState < boolean > false;
const [state, setState] = useState([]);

const handle = () => {
  setLoading(true);
  fetch(`https://jsonplaceholder.typicode.com/posts`, requestResp).then(
    (response) => {
      response.json();
      console.log(response.json());
      setState(response.json());
      setLoading(false);
    }
  );
};

in your return

if (Loading) {
  return <h1>loading</h1>;
} else {
  return (
    <div>
      <pre>{JSON.stringify(state)}</pre>
    </div>
  );
}
  • Related