React javascript promise useState를 render할 시 아무것도 렌더가 되지 않을 때 해결법

나의 재물운? 연애운은?

AI가 봐주는 내 사주팔자 - 운세박사

https://aifortunedoctor.com/

React javascript promise useState를 render할 시 아무것도 렌더가 되지 않을 때 해결법

영리치 0 938 2023.02.07 17:23

Promise 객체들을 useState Array에 넣을 때 아무것도 렌더가 안되는 이슈가 자주 발생함

그럴 때는 아래처럼 처리해주면 된다.


coordMatrix.map((coords, idx) => {
const coordsString = coords.join(";");
const matchLineRes = getMatch(coordsString);
// console.log("matchLineRes", matchLineRes);
// console.log("idx", idx);
// matchedLine.push(matchLineRes);
tempCoord.push(matchLineRes);
// setMatchedLine([...matchedLine, matchLineRes]);
// matchedLine.push(matchLineRes);
});
const responses = await Promise.all(tempCoord);
setMatchedLine(responses);



{matchedLine.map((line, idx) => {
}


아래 부분이 핵심임.

const responses = await Promise.all(tempCoord);
setMatchedLine(responses);



I am using react-map-gl. I got Array of geojson format LineStrings from several API request. I want to render the LineStrings after fetching apis. But It don't render. How can I solve it? I want to use Layer, Source of react-map-gl.

import React, { useState, useEffect } from 'react'; import { StaticMap, Source, Layer } from 'react-map-gl'; const MyMap = () => { const [lines, setLines] = useState([]); useEffect(() => { async function fetchData() { const promises = [ fetch('https://api.example.com/lines1'), fetch('https://api.example.com/lines2'), fetch('https://api.example.com/lines3') ]; const responses = await Promise.all(promises); const data = await Promise.all(responses.map(r => r.json())); setLines(data); } fetchData(); }, []); return ( <StaticMap style={{ width: '100%', height: '100%' }} mapboxApiAccessToken={process.env.REACT_APP_MAPBOX_ACCESS_TOKEN} mapStyle="mapbox://styles/mapbox/light-v10" > {lines.map((lineData, index) => ( <Source key={index} type="geojson" data={lineData}> <Layer type="line" layout={{ 'line-join': 'round', 'line-cap': 'round' }} paint={{ 'line-color': '#888', 'line-width': 8 }} /> </Source> ))} </StaticMap> ); }; export default MyMap;


In this example, fetchData is used to retrieve the LineStrings data in GeoJSON format from multiple APIs and set it as an array of GeoJSON objects in the state. Then, Source component is used inside a loop to provide each set of GeoJSON data to the map and the Layer component is used to define the appearance of the lines. The StaticMap component provides the map container and the mapbox styles. Note that you'll need a valid Mapbox access token to use this component.






Comments

나의 재물운? 연애운은?

AI가 봐주는 내 사주팔자 - 운세박사

https://aifortunedoctor.com/

Category
Magazine
훈남/훈녀
 
 
 
상점
Facebook Twitter GooglePlus KakaoStory NaverBand