-1

When using array map method, the browser page is blank and in the console I receive an error:

array.map not a function

Although when I comment array.map before rendering the page and after page gets renderd I uncomment it and it works fine.

const movieDesc = useSelector((state) => state.movieDesc);
const [allVideo, setallVideo] = useState("");
const getAllVido = async () => {
try {
  const res = await axios.get(
    `https://api.themoviedb.org/3/${movieDesc.desc.media_type}/${movieDesc.desc.id}/videos?api_key=${process.env.REACT_APP_API_KEY}`
  );
  console.log(res.data);
  setallVideo(res.data.results);
} catch {
  console.log(Error);
}
};
useEffect(() => {
  getAllVido();
}, []);

JSX code:

<p className="movieDesc__trailer">All Video</p>
  {allVideo?.map((video) => (
    <>
      <p key={video.id}>{video.name}</p>
      <iframe
        key={video.id}
        className="movieDesc__trailerVideo"
        src={`https://www.youtube.com/embed/${video.key}`}
        title={video.name}
        frameborder="0"
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        allowfullscreen
      ></iframe>
    </>
  ))}

  <p className="movieDesc__wrap">Wrapping Up</p>
Ari Seyhun
  • 11,506
  • 16
  • 62
  • 109
  • 2
    Try setting the initial state to an array instead of a string `const [allVideo, setallVideo] = useState([]);` – jkoch Mar 20 '22 at 05:44

3 Answers3

1

You're initializing allVideo as a string. .map does not exist on the string prototype, so it's not telling you something false. Initialize it to an empty array and you will be fine.

const [allVideo, setallVideo] = useState([]);

Also make sure that res.data.results is an array, or you will get the same error.

Joshua Wood
  • 435
  • 5
  • 18
1

You have initiated allVideo as a string

const [allVideo, setallVideo] = useState("");

When the component mount for the first time, it tries to map allVideo as a result you are getting the error

try initiating allVideo as an empty array

const [allVideo, setallVideo] = useState([]);
Tanvir Ahmed
  • 357
  • 2
  • 15
0

When you set the useState hook's default value to an empty string, then you are accessing a string's methods and properties.

To fix this issue, simply change Line 2 in your JavaScript code to the following.

const [allVideo, setAllVideo] = useState([]); // Changes have been made here
Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33