Answer the question
In order to leave comments, you need to log in
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>;
}
}
export class ServiceResponseGeneric<T> extends ServiceResponse{
Value: Array<T>
//он не наследует ничего такого важного, типа errorMessage: string и всякое такое
constructor(val: Array<T>) {
super();
this.Value = val
}
}
export class UserDto {
Id: string = ""
Login: string = ""
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question