Home > front end >  Why my screen goes white on calling API for first time but it works on second time
Why my screen goes white on calling API for first time but it works on second time

Time:07-03

As I mentioned in title my screen goes white on calling API for first time but when I refresh and inputs the value it works properly

on console the error is : Uncaught TypeError: Value.map is not a function

  const [data, setData] = useState({});
  const [user, setUser] = useState("");
  const [Value, setValue] = useState("");

  const APIurl = async () => {await axios.get(`https://api.github.com/users/${user}`).then((response) => { setData(response.data);
      console.log(response.data); });};

  const APIurl1 = () => {
    axios.get(`https://api.github.com/users/${user}`   `/repos`).then((response) => {
        setValue(response.data);
        console.log(response.data);
      }); };

  const handleKey = (e) => {
    if (e.key === "Enter") {
      APIurl();APIurl1();}};

  return (
    <>
      <div className="bbody">
        <input
          id="search-bar"
          onChange={(event) => setUser(event.target.value)}
          placeholder="Enter User"
          type="text"
          onKeyPress={handleKey}
        />

        {!data.name ? (
          <div>
            <p className="errorMsg">No Data Found</p>
          </div>
        ) : (
          <>
                <div className="inner-img">
                  <img src={data.avatar_url} alt="" />          
                  <h2>{data.name}</h2>
                  <p>{data.bio}</p>
                  <div id="repos">
                    {Value.map((value) => {
                      return (
                        <a key={value.id} href={value.html_url} target="_blank">
                          <button id="repos-link">{value.name}</button>
                        </a>
                      );
                    })}
                 ```

I m trying to get Github profile of a person by inputting name in the input field and extracting the info from the API.


CodePudding user response:

Because the initial state of Value is an empty string. Nothing is there, so there's nothing to map. When you use setValue after typing in the input its state is updated to reflect whatever you've typed, so only then can you map over Value.

CodePudding user response:

You should check if there is Value, add Value && like so:

 {Value &&
   Value?.map((value) => {
     return (
       <a key={value.id} href={value.html_url} target="_blank">
         <button id="repos-link">{value.name}</button>
        </a>
      );
  })}
  • Related