0

there is a way to use useState with an interface type?

This is what i'm tryint to do :

const [movie, setMovie] = useState(null);

[...]

.then((responseJson) => {
            var movie: Movie = {
                id : id,
                title: responseJson.original_title,
                backdrop: "https://image.tmdb.org/t/p/original" + responseJson.backdrop_path,
                note: responseJson.vote_average,
                numberNote: responseJson.vote_count,
                year: responseJson.release_date,
                runtime: responseJson.runtime,
                genre: responseJson.genres,
                plot: responseJson.overview,
            };
            setMovie(movie);
        })

But there is error on type.

My interface:

interface Movie {
    id: number;
    title: string;
    backdrop: string;
    note: number;
    numberNote: number,
    year: number,
    runtime: number,
    genre: {id: number, name: string}[],
    plot: string
}

according to this post : Set types on useState React Hook with TypeScript.

I can try to do something like that :

const [movie, setMovie] = useState<Movie>({id: 0,
        title: "",
        backdrop: "",
        note: 0,
        numberNote: 0,
        year: 0,
        runtime: 0,
        genre: [{id: 0, name: ""}],
        plot: ""});

But it doesn't look clean and I don't think this is the good solution to put random value in the first state.

samuel
  • 477
  • 7
  • 21

1 Answers1

4

You can imply state type in the following way:

const [movie, setMovie] = useState<Movie|null>(null);
glinda93
  • 7,659
  • 5
  • 40
  • 78