Server requests (Fetching data) in react

Posts fetched from https://jsonplaceholder.typicode.com/posts

Loading posts.....

    As you can see in below example we are using useEffect and useState hooks to load data from server.

    
       const [data, setData] = useState(null);
       const [loading, setLoading] = useState(true);
       const [error, setError] = useState(null);
    
    useEffect(() => {
       const getPosts = async () => {
         try {
           const response = await fetch(
             'https://jsonplaceholder.typicode.com/posts?_limit=3'
           );
           if (!response.ok) {
             throw new Error(
               'Response is not ok'+ response.status
             );
           }
           let postData = await response.json();
           setData(postData);
           setError(null);
         } catch(err) {
           setError(err.message);
           setData(null);
         } finally {
           setLoading(false);
         }  
       }
       getPosts()
     }, [])
    
    
    
    
    return(
     <div>
     <h3>Posts fetched from https://jsonplaceholder.typicode.com/posts</h3>
     {loading && <div>Loading posts.....</div>}
     {error && (
       <div>Error occured fetching data - {error}</div>
     )}
     <ul>
       {data &&
         data.map(({ id, title }) => (
           <li key={id}>
             {id} {title}
           </li>
         ))}
     </ul>
    </div>
        )
    
    

    Web development and Automation testing

    solutions delivered!!