D
D
dc65k2021-06-04 12:53:07
typescript
dc65k, 2021-06-04 12:53:07

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,
}


And what is important, how to type the response with an asynchronous request?
interface ITwitter {
    userId: number,
    id: number,
    title: string,
    completed: boolean,
}

const response = await fetch(url).then(response => response.json());


Ex.1
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 answer(s)
A
Aetae, 2021-06-04
@Aetae

1. React has a helper PropsWithChildren<Props>. But under the hood it just does this:

type PropsWithChildren<P> = P & { children?: ReactNode };

...upd: understood a bit)
If you need a render prop in children, then explicitly tap it, no tricks:
type TwitterProps = {
    children: (user: string) => ReactNode
}

2. How to type: 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 question

Ask a Question

731 491 924 answers to any question