State returning Undefined

Asked

Viewed 229 times

0

I’m not much for asking, right, but it’s keeping me up at night... I have the following function to format dates

const DataFormat = (props) => {
    const data = props.split('T');
    const [year, month, day] = data[0].split("-")
    const formateddata = day + " de " + month + " de " + year
    return "Atualizado em: " + formateddata
}

export default DataFormat

While in the other:

import React, { useState, useEffect } from 'react';
import api from '../services/api'
import { useParams } from 'react-router-dom'
import DataFormat from '../functions/dataformat'

const Produto = () => {
    const { listaId } = useParams()
    const [list, setList] = useState([])

    useEffect(async () => {
        const response = await api.get(`getproduto/${listaId}`)
        setList(response.data)
    }, [])

    return (
        <div>
            <div className="titleBox">
                <p className="updatedTime">{DataFormat(list.updatedAt)}</p>
            </div>
        </div>
    )
}

export default Produto

This updatedAt even returns me the right date, but when it passes inside the function it turns Undefined D:

"Typeerror: Cannot read Property 'split' of Undefined"

I look forward to the solution ;'(

1 answer

1


The problem is in your useEffect. It may seem strange, but it is not possible to do the useEffect function asynchronously like this. That being said, the error is occurring precisely because the value of list.updateAt has not yet been updated when passed to the function DataFormat. The right way would be this:

useEffect(() => {
    async function fetchAPI() {
        const response = await api.get(`getproduto/${listaId}`)
        setList(response.data)
    }
    fetchAPI()
}, [])

Two tips:

  1. It may be interesting to use specific libraries to work with dates, I recommend the Moment js..
  2. The correct name of your function would be dateFormat, with "e" instead of "a". "data" translation is "data".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.