Answer the question
In order to leave comments, you need to log in
How to correctly type React code (children and response with asynchronous request)?
Hello. Can you please tell me how to correctly type the following code?
The points that are most interesting are the typing of children:
type TwitterProps = {
children: any,
}
interface ITwitter {
userId: number,
id: number,
title: string,
completed: boolean,
}
const response = await fetch(url).then(response => response.json());
import React, {useState, useCallback, ReactFragment} from 'react';
import './App.css';
const url = 'https://jsonplaceholder.typicode.com/todos/1';
function Loading() {
return <div>Loading</div>
}
type BadgeProps = {
info: string
}
function Badge({info}: BadgeProps) {
return (
<div>
<p>{info}</p>
<p>Badge</p>
</div>
)
}
interface ITwitter {
userId: number,
id: number,
title: string,
completed: boolean,
}
type TwitterProps = {
// children: React.ReactNode,
children: any,
}
type TwitterState = {
userId: string | null
}
class Twitter extends React.Component<TwitterProps, TwitterState> {
constructor(props: TwitterProps) {
super(props);
this.state = {
userId: null,
}
}
/*
state = {
userId: null
}
*/
async componentDidMount() {
const response = await fetch(url).then(response => response.json());
console.log(response);
const {userId} = response;
this.setState({userId})
}
render() {
console.log(this.props);
const {children} = this.props;
const {userId} = this.state;
return children(userId);
}
}
class App extends React.Component<{}, {}> {
render() {
return (
<Twitter>
{
(user: string) => user === null
? <Loading/>
: <Badge info={user}/>
}
</Twitter>
)
}
}
Answer the question
In order to leave comments, you need to log in
1. React has a helper PropsWithChildren<Props>
. But under the hood it just does this:
type PropsWithChildren<P> = P & { children?: ReactNode };
type TwitterProps = {
children: (user: string) => ReactNode
}
const response: ITwitter = ...
. Only if some thread of crap arrives can it break at runtime, so either you trust the server, or use some thread or lib for additional verification live.)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question