Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
Cannot read properties of undefined (reading > 'map')

I'm fetching data from an API and want to show them as texts, the title and desc worked fine but the categories didn't, the error I get is:

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

The Code:

export default function SinglePost() {

      const [post, setPost] = useState({});
      const [title, setTitle] = useState("");
      const [desc, setDesc] = useState("");
      const [categories, setCategories] = useState("");
      
        useEffect(() => {
        const getPost = async () => {
          const res = await axios.get("/posts/" + path);
          setPost(res.data);
          setTitle(res.data.title);
          setDesc(res.data.desc);
          setCategories(res.data.categories);
        };
        getPost()
      }, [path]);
      
      <div className="singlePost">
                <div className="singlePostInfo">
               <div className="postCats">
              {post.categories.map((c) => (
                    <span className="postCat" key={c._id}>
                      Category: {c.name}
                      </span>
                  ))}
              </div> 
      </div>
    }

I don't know where my mistake is!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you need to update your render method to render categories from the state and the default value of categories state should be [] instead of ""

Change const [categories, setCategories] = useState("") to const [categories, setCategories] = useState([])

Change post.categories.map to categories.map and it should work!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda