1

I'm using React hooks and axios, based on a previous example to fetch data from multiple endpoints. I'm having troubles rendering the data, though.

I've forked a precious example where you can see the issue. Can someone help and point out where I'm going wrong with the .map() ...?

Thank you!!

2
  • where is the .map() in the code sample? Commented Oct 12, 2019 at 20:25
  • Put a minimal reproducible example in the question. Commented Oct 12, 2019 at 20:32

1 Answer 1

1
setGitData({ data: respGlobal.data, repos: respGlobal.data });

respGlobal was used in two places

{resp.data}

Would have not worked in JSX because it is an object and it expects a string

Full working example:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import axios from "axios";

import "./styles.css";

const username = "mayankshubham";
function App() {
  const [resp, setGitData] = useState({ data: null, repos: null });

  useEffect(() => {
    const fetchData = async () => {
      const respGlobal = await axios(
        `https://api.github.com/users/${username}`
      );
      const respRepos = await axios(
        `https://api.github.com/users/${username}/repos`
      );

      setGitData({ data: respGlobal.data, repos: respRepos.data });
    };

    fetchData();
  }, []);

  console.log("render");
  if (resp.data) {
    console.log("d", resp.data, resp.repos);
  }

  return (
    <div>
  <h1>Hello </h1>
    <div>{JSON.stringify(resp.data)}</div>
    <br />
    <div>{JSON.stringify(resp.repos)}</div>
  </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up to request clarification or add additional context in comments.

1 Comment

This is great. Thanks very much, I am fetching data from another API and it did work. I was basically trying to follow the React docs to render the list const { resp } = data; const bookList = data.map((genre, i) => <li key={genre.i} name={genre.name} />); and then just render ` {bookList}` in the return ... & .map() was throwing error....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.