rahul Dev
rahul Dev

Reputation: 25

How to loop through all the Axios Api data and pass it to another container with React Hooks

Would it be possible to send all the data from Fetching Api data from TV Maze section and send it to FetchApiData data={data}? So that I can use that value in ApiData.js component and display all the images. Currently, I'm only able to send one data or image link if I specify the values like request.data[0] or request.data1 etc.. I tried using map(()) inside the Fetching Api data from TV Maze section. When I try to pass that data to FetchApiData component, it throws the following error - cannot read medium of null. Basically, I'm trying to create a website that would fetch Api from the TV maze website based on the value the user types on a form and then show all the TV show images which have similar titles. Any other way to display all the images fetched from the Api is okay too. I'm a beginner, so if you are unclear about the issue please let me know. Thanks in advance

App.js

import React, {useState, useEffect} from 'react';
import Nav from "./Nav";
import UseForm from "./Form"
import FetchApiData from './ApiData'
import axios from 'axios';


function App(){
    //fetching values typed by the user
const [inputValue, setInputValue] = useState({
        search: "",
        contactName:"",
        contact:""
    });
//when form is submitted run this
function onFormSubmit(event){
        setInputValue(inputValue.search)
        event.preventDefault();
    }

//fetching Api data from TV Maze    
const [data, setData] = useState([{}])
    useEffect(()=>{
        async function fetchData(){
            try{
                const request =  await axios.get(`http://api.tvmaze.com/search/shows?q=${inputValue}`) 
                let appData =  request.data[0].show.image.medium ////want to loop through all the images in this array. For eg; request.data[1].show.image.medium and so on.Not just request.data[0] 
                setData(appData)  
                return appData
                } 
            catch(err){
                console.log(err)
                }
        
    }  fetchData()
    }, [inputValue])

    return (
    <div>
        <Nav 
        src={`${process.env.PUBLIC_URL}/images/logo.png`}
        title = "CONTACT US"
        />
        <UseForm inputValue={inputValue} setInputValue={setInputValue}
            onFormSubmit = {onFormSubmit}
        />
        {/* {send all the looped images from api here. Currently it is only sending one image} */}
            <FetchApiData data={data}/>
    </div>)
}

export default App

ApiData.js

import React, {useState, useEffect} from 'react';
import axios from 'axios';

// for each image fetched from App.js file i.e(<FetchApiData data={data}/>) return this div....
const FetchApiData = ({data}) =>{
    return (
            <div className="section-image">
                <img src={data} alt=""/>
            </div>
            
            ) 
}


export default FetchApiData

Form.js

import React, {useState} from 'react';


function UseForm({inputValue, setInputValue, onFormSubmit}){

    function handleChange(e){
        const {name, value} = e.target;
        setInputValue(previousValue=>{
            if(name === "search"){
                return{
                    search: value,
                    contactName:previousValue.contactName,
                    contact:previousValue.contact   
                }
            }
        })
    }


    return ( 
        <div className="form-container">
            <div className="input-div">
                <form onSubmit={onFormSubmit}>
                    <input className="form-input" onChange={handleChange} type="text" name="search" value={inputValue.search} placeholder="Search TV Shows"/>
                    <button type="submit" className="btn">Submit</button>    
                </form>   
            </div>
        </div>)
}



export default UseForm;

console.log

Console.log

Console.log 2nd half console.log-2nd half

Now there's a new error. I pasted these URL's in postman and sent a get request. There weren't any issues. enter image description here

This is one of the URLs [https://static.tvmaze.com/uploads/images/medium_portrait/31/78286.jpg][4]

[4]:

Upvotes: 0

Views: 772

Answers (1)

Priyank Kachhela
Priyank Kachhela

Reputation: 2635

You just need to map response data and extract image urls.

Try something like below:-

  useEffect(() => {
    async function fetchData() {
      try {
        const request = await axios.get(
          `http://api.tvmaze.com/search/shows?q=${inputValue}`
        );

        let appData = request.data.map(innerData => innerData.show?.image?.medium)
        setData(appData);
      } catch (err) {
        console.log(err);
      }
    }
    fetchData();
  }, [inputValue]);

Upvotes: 1

Related Questions