@adizh

Как загружать прелоадер по fetch api и сделать так, чтобы он исчез после получения данных?

Я хочу загрузить прелоадер до тех пор,пока апишка грузится и сделать так,чтобы он исчез после получе-
ния данных. Но у меня не получается

import React,{useState}  from 'react';

import axios from 'axios';
import backImg from '../image/illustration (3).png'
import Plan from './Plan/Plan';
import Error from './Error'
import SpeedInfo from './SpeedInfo'
const Speed = ()=>{
    const [weatherData,setWeatherData]=useState({})
    const [city,setCity]=useState('')
    const [load,setLoad]=useState(false)
    const speedSubmit=(e)=>{
    e.preventDefault()
    setLoad(true)
    axios(`https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${city}`).then(({data}) => {
    console.log(data)    
    return setWeatherData(data);
    }).catch(() => {
        setWeatherData({...weatherData,error:true})
    })
};
  
    

const inputHandler = (e) => {
    console.log(e.target.value);
    setCity(e.target.value)
};

    return(
        <div>         
<div className='speed'>
<div className='speed_check'>
<div className='speed_title'>Check Your Website Speed </div>
    <div className='speed_text'>
    Distinctively exploit optimal alignments for intuitive bandwidth.
Quickly coordinate e-business through revolutionary.
    </div>
    <form   onSubmit={speedSubmit} className='speed_form'>
            <input type='url' placeholder='WEB URL'  onChange={inputHandler}/>
            <button type='submit' className='speed_btn'>Submit</button>
    </form>
    {(Object.entries(weatherData).length === 0) ? '' : weatherData.error ? <Error/> :
                <SpeedInfo weatherData={weatherData} load={load} setLoad={setLoad} />
            }
</div>
<div className='speed_img'> 
    <img src={backImg}/>
</div>
</div>
<Plan/>
        </div>
    )
}
export default Speed

компонент,который должен появиться после loader:
import React from 'react';
import './Speed.css';


const SpeedInfo = ({weatherData,load,setLoad}) => {
        console.log(weatherData.id)
    return (
       
      <div>
       {load === false?'loading':false}
  
<div className='speed_info_ofwebsite'>
            <div>
                <h5>Results: </h5>
              <div>  <div className='site_name'><strong > Website url: </strong> <a className='link' href="#">{weatherData.id}</a></div>
                <div className='site_name' id='speed_of'><strong className='website_speeed'> Website speed: </strong><span className='speed_website_cat'> {weatherData.loadingExperience.metrics.CUMULATIVE_LAYOUT_SHIFT_SCORE.category}</span></div>
                </div>
              <div><div className='site_name'><strong> Version:</strong> {weatherData.lighthouseResult.configSettings.formFactor}</div>
                <div className='site_name'><strong> Total elements: </strong> {weatherData.lighthouseResult.audits['dom-size'].displayValue}</div>
               </div>
             <div>
               <div className='site_name'><strong> Website was displayed in : </strong> {weatherData.lighthouseResult.audits['speed-index'].displayValue}</div>
                <div className='site_name'><strong> Website size: </strong> {weatherData.lighthouseResult.audits['total-byte-weight'].displayValue}</div>

             </div>
                       </div>
            </div> 
      </div>
            
    );
};

export default SpeedInfo;
  • Вопрос задан
  • 763 просмотра
Пригласить эксперта
Ответы на вопрос 1
GreyCrew
@GreyCrew
Full-stack developer
Добавьте ещё одно состояние load, которое по умолчанию true.
После запроса сделайте его false.

П.С. Скоро выйдет 18 реакт и там уже можно будет свободно использовать suspense и всё такое))
https://ru.reactjs.org/docs/concurrent-mode-suspen...
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы