Overview: I have two components: ComponentA and ComponentB, I would like to make a POST request to my API and store the returned JSON string into a useState hook, and then pass that state to componentB. In ComponentB I would like to use the .map() function to iterate through the prop's contents.
API response JSON Data Structure: [{object: 1, name: 'bob'},{object: 2, name: 'joe'}...]
Here is my state hook definition:
const [data, setData] = useState([]);
My API call:
const handleSubmit = () => {
console.log("Function Called");
fetch("/post", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formik.values),
})
.then((response) => response.json())
.then((res) => {
console.log(typeof res);
setData(res);
})
.catch((err) => {
console.log(err);
});
};
and my ComponentB .map() function
<tbody>
{props.responses.length > 0 ? (
props.responses.map((response) => (
<tr
class={
tableRow === "" ? (tableRow = "table-primary") : (tableRow = "")
}
>
<td>{response.object}</td>
<td>{response.name}</td>
</tr>
))
) : (
<tr></tr>
)}
</tbody>
whenever I make the API call I get this error:
Error: Objects are not valid as a React child (found: object with keys {object, name}). If you meant to render a collection of children, use an array instead.
is it possible to set the response in the state as a JSON object and pass it to ComponentB? If so what am I doing wrong?
Or do I need to pass it off as a string and then JSON.parse() in ComponentB? (the only problem with this is that JS throws a cors error, why is that?