Answers for "react hooks typescript axios get request"

0

react hooks typescript axios get request

// Example - get posts:

//IUser.interface.ts
export default interface User{
    id : string;
    userName : string;
    password : string;
    firstName : string;
    lastName : string;
    workplace : string;
    friendsList: number[];
}

// IPost.interface.ts
import IUser from "./IUser.interface";

export default interface IPost{
    id:             string;
    picture:        ImageBitmap;
    caption:        string;
    taggedUsers:    IUser[];
    tags:           string[];
    usersLiked:     IUser[];
    location:       Location;
}


// Page where you want to receive the data - MainPage.tsx:   	
    const [posts, setPosts] = useState<IPost[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string>("");

    const getPosts = () => {
        axios.get<IPost[]>(process.env.REACT_APP_BASE_API_URL + '/posts', {
            headers: {
                "Content-Type": "application/json"
            },
        })
            .then(response => {
                setPosts(response.data);
                setLoading(false);
                console.log(response.data);
            })
            .catch(ex => {
                const error = ex.response.status === 404
                    ? "Resource Not found"
                    : "An unexpected error has occurred";
                setError(error);
                setLoading(false);
            });
    }
    
        return(
        <div className="mainpage">
                { posts && posts.map((post: IPost) => {
                    return (
                     // Do something for every post in the posts array you received
                    )
                })}
        </div>
    )
Posted by: Guest on October-11-2021

Code answers related to "TypeScript"

Browse Popular Code Answers by Language