I'm developing an app in react-native. I get the data by requesting get through api. What I want to do is to show it right away on the screen when it comes to that page from the previous page. However, when you come to the page, 'faceShape.map is not a function' error occurs. This is the code I wrote.
const [faceShape, setFaceShape] = useState();
axios(config)
.then(function (res) {
let face = [];
res.data.data.map((u) => {
switch (u.faceType) {
case "circle":
face.push({ faceType: "둥근형", imgUrl: u.imgUrl });
break;
case "egg":
face.push({ faceType: "계란형", imgUrl: u.imgUrl });
break;
case "square":
face.push({ faceType: "사각형", imgUrl: u.imgUrl });
break;
case "reverseTriangle":
face.push({ faceType: "역삼각형", imgUrl: u.imgUrl });
break;
}
});
setFaceShape(face);
})
(...)
{faceShape.map((data) => (
<>
<TouchableHighlight style={styles.skincolorcontainer}>
<>
<SvgCssUri uri={data.imgUrl} width="50%" height="20%" />
<Text style={styles.skintext}>{data.faceType}</Text>
</>
</TouchableHighlight>
</>
))}
I wonder why the data doesn't go over immediately when I first enter the page. Please give me an answer.
Try something like this
import { useEffect } from "react"; // At the top
(...)
const [faceShape, setFaceShape] = useState([]);
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
GetData();
});
return unsubscribe;
}, [navigation]);
const GetData = async () => {
try {
axios(config).then(function (res) {
let face = [];
res.data.data.map((u) => {
switch (u.faceType) {
case "circle":
face.push({ faceType: "둥근형", imgUrl: u.imgUrl });
break;
case "egg":
face.push({ faceType: "계란형", imgUrl: u.imgUrl });
break;
case "square":
face.push({ faceType: "사각형", imgUrl: u.imgUrl });
break;
case "reverseTriangle":
face.push({ faceType: "역삼각형", imgUrl: u.imgUrl });
break;
}
});
setFaceShape(face);
});
} catch (error) {}
};
(...)
{
faceShape.map((data) => (
<>
<TouchableHighlight style={styles.skincolorcontainer}>
<>
<SvgCssUri uri={data.imgUrl} width="50%" height="20%" />
<Text style={styles.skintext}>{data.faceType}</Text>
</>
</TouchableHighlight>
</>
));
}
What I did here is that whenever this screen comes in focus
it will fetch data and update it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments