P
P
priority2020-06-21 16:19:01
typescript
priority, 2020-06-21 16:19:01

Why fetch response becomes undefined?

Hello.
The problem is that when I make a fetch request using the useEffect hook, I kind of get valid information in the first promise, and in the next promise, when I want to save this info to a variable, it is already undefined.
Here is the code:

const ChatList: React.FC = () => {
    const [error, setError] = useState(null);
    const [isLoaded, setLoaded] = useState(false);
    const [response, setState] = useState<ServiceResponseGeneric<UserDto>>();

    useEffect(() => {
        fetch(URL)
            .then(result => result.json() as Promise<ServiceResponseGeneric<UserDto>>)
            .then(
                (result) => {
                    setLoaded(true)
                    setState(result)
                    console.log(result) // здесь ничего уже не отображает, а если бы я поставил лог в начало, перед setLoaded, то все вывело бы. Как будто после setLoaded все куда то не туда идет
                },
                (error) => {
                    setLoaded(true)
                    setError(error)
                }
            )
    }, [])

    if (error) {
        return <div>Ошибка</div>
    } else if (!isLoaded) {
        return <div>Загрузка</div>
    } else {
        return <div className="chatList">
            <div className="messagesTitle">Последние сообщения</div>
            {
                Array.from(response?.Value!).map(item =>
                    <ChatListItem
                        chatId={item.Id}
                        chatName={item.Login}
                        messagePreview="Заглушка"
                        sentTime="21:14"/>)
            }
        </div>;
    }
}


Just in case, here are the used
ServiceResponseGeneric classes
export class ServiceResponseGeneric<T> extends ServiceResponse{
    Value: Array<T>
//он не наследует ничего такого важного, типа errorMessage: string и всякое такое
    
    constructor(val: Array<T>) {
        super();
        this.Value = val
    }
}


UserDto
export class UserDto {
    Id: string = ""
    Login: string = ""
}


There are many answers to this question on the internet and they seem to be good, but it doesn't work for me. The server returns everything is normal.
Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question