Using React Native Expo, I have a MapView screen which displays information of a Marker (Title, Description, Image etc.) on a bottom screen. Currently I have a function which when a marker is pressed the marker information is passed to a variable called MarkerInfo and displayed on the bottom screen. However when the component is initialised there is no information displayed in the bottomsheet.
I would like to display a message prompting users to select a marker.
Here is the current code block including the pressMarker function:
// ## Attempting to set intial values prompting users to select a marker for more info
const state = {
MarkerInfo: {
PreviewTitle: "Select A Marker.",
Description: "Press on a marker to get location information"
}
};
// ## Without the code above this all works fine:
// ## Setting the currently selected marker as variable (in an array) "MarkerInfo".
const [MarkerInfo, setMarkerInfo] = useState([]);
const pressMarker = (i) => {
setMarkerInfo(i);
console.log(i)
return(MarkerInfo)
};
Here is example what the marker info array looks like, when a marker is pushed.
Object {
"Description": "Former historic palace housing huge art collection, from Roman
sculptures to da Vinci's 'Mona Lisa.",
"ImageUrl": "*** My firebase storage URL",
"Latitude": 48.86074344,
"Location": "Paris",
"Longitude": 2.337659481,
"PreviewTitle": "Louvre",
"Title": "Louvre Museum",
"id": 64,
"key": "63",
}
However currently the bottom sheet is displaying nothing until I hit a marker. So it seems my initial variable definition of Marker info is not executing like I would hope.
What do I need to change with the initial declaration? I've also tried doing a function using component did mount and returning the initial marker info with no luck.
CodePudding user response:
try to use
setMarkerInfo([...i]);
instead using
setMarkerInfo(i);
CodePudding user response:
you don't need to use lifecycle methods like componentDidMount
if you are using hooks. And as it seems the way you try to initialize the state in the first place seems wrong when you are using hooks and functional components as suggested by React.
you have to pass the same object as the object you will have on the state when you select an item from the array stat value in the useState
declaration.
so your code should be
const initialState = {
"Description": "Press on a marker to get location information",
"ImageUrl": "",
"Latitude": 0,
"Location": "",
"Longitude": 0,
"PreviewTitle": "Select A Marker.",
"Title": "Select A Marker.",
"id": 0,
"key": "",
}
const [MarkerInfo, setMarkerInfo] = useState(initialState);
ps I am assuming that your PreviewTitle and Description is the one you're displaying on the screen