Home > OS >  array.map not a function
array.map not a function

Time:03-20

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>

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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([]);
  • Related