Skip to content
Advertisement

How to fix “TypeError: props.scoreboard.map is not a function”, only after refresh

I’m having an odd issue when I’m trying to loop over my response from my backend. I’ve seen similar questions and they seem to point to the response not being an array, but logging my response does indeed result in an array.

I’m passing the scoreboard prop to the scoreBoardItem which will map over the props and return what I want.

import { useState, useEffect } from 'react';
import ScoreboardItem from './ScoreboardItem';

function Scoreboard(props) {
  const [name, setName] = useState('');
  const [scoreboard, setScoreboard] = useState('');

  const winStreak = props.winStreak;
  const lowestWinStreak = props.lowestWinGuess;
  const handleOnSubmit = async (e) => {
    e.preventDefault();
    let result = await fetch('http://localhost:5000/', {
      method: 'post',
      body: JSON.stringify({ name, winStreak, lowestWinStreak }),
      headers: {
        'Content-Type': 'application/json',
      },
    });
    result = await result.json();
    console.warn(result);
    if (result) {
      alert('Data saved successfully');
      setName('');
    }
  };

  const getScoreboard = async () => {
    let response = await fetch('http://localhost:5000/');
    let result = await response.json();
    console.log(result);
    setScoreboard(result);
  };

  //useeffect to get the scoreboad data from the server
  useEffect(() => {
    getScoreboard();
  }, []);

  return (
    <div className=" ">
      <h2 className="text-xl">High Scores</h2>
      <div>
        Current Streak: {winStreak}, Lowest Winning Guess: {lowestWinStreak}
      </div>
      <form>
        <input
          className="text-center"
          type="name"
          placeholder="Enter Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <button
          className="text-lg border-1 bg-yellow-500 border-yellow-500 p-1 m-2 rounded-lg hover:bg-green-500 active:bg-gray-500 align-content: center;"
          type="submit"
          onClick={handleOnSubmit}
        >
          Submit
        </button>
      </form>

      <ScoreboardItem scoreboard={scoreboard} />
    </div>
  );
}

export default Scoreboard;

This is the ScoreBoardItem component, strangely if I comment out the map function, rerun then uncomment it; it will work. It will then stop working again after refreshing.

 function ScoreboardItem(props) {
  console.log(props);
  // maps through scoreboard and displays name and high streak
  return (
    <div>
      {props.scoreboard.map(({ name, winStreak, lowestWinStreak }) => (
        <div className="border-b border-purple-500 pb-4 my-2">
          <h1 className="text-1xl text-center">{name}</h1>

          <div> Winstreak: {winStreak}</div>
          <div> Lowest Winning Guess: {lowestWinStreak}</div>
        </div>
      ))}
    </div>
  );
}

export default ScoreboardItem;

Appreciate any thoughts on this matter.

Advertisement

Answer

This happens because when defining const [scoreboard, setScoreboard] = useState(''); you don’t define it with the initial value of [”]

Replace it with const [scoreboard, setScoreboard] = useState(['']);

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement