we got an issue, project on : Symfony 4, Api-Platform, React and other packages.
We create SearchBar.jsx and want to show the results on Maps.jsx
We want to transfert perfectAdress
from the usestate of SearchBar.jsx to const position = []
on Maps.jsx
We got a good json response on our console log but we don't know how to retrieve the data and pass them.
We follow the trails of Context API, SWR and others, but we are stuck, so if you can help us we will be so happy.
Here's our code :
SearchBar.jsx :
import React, {useState} from "react";
import axios from 'axios';
import { withRouter } from 'react-router-dom';
import { toast } from "react-toastify";
const SearchBar = ({ history }) => {
const [search, setSearch] = useState("");
const [address, setAddress] = useState([]);
const [perfectAddress, setPerfectAddress] = useState([]);
const handleSearch = ({ currentTarget }) => {
setSearch(currentTarget.value);
}
const handleSubmit = async event => {
event.preventDefault();
try {
const data = await axios.get("https://nominatim.openstreetmap.org/search?q="+search+"&format=json&polygon=1&addressdetails=1")
.then(reponse => reponse.data[0])
setAddress(data);
const latLong = [data['lat'], data['lon']];
setPerfectAddress(latLong);
history.push("/leaflet")
}
catch (error) {
toast.error("Impossible de charger les données");
}
}
//history.replace("/leaflet")
return (
<>
<form onSubmit={handleSubmit}>
<div className="md-form active-cyan active-cyan-2 d-flex mb-3">
<input
className="form-control mr-3"
type="text"
value={search}
onChange={handleSearch}
placeholder="Rechercher..."
aria-label="Search"
/>
<button type="submit" className="btn btn-success">
Rechercher
</button>
</div>
</form>
</>
);
};
export default withRouter(SearchBar);
Json Reponse from SearchBar.jsx : Json Response
Maps.jsx :
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Map, Marker, Popup, TileLayer } from "react-leaflet";
import { toast } from "react-toastify";
const Maps = (props) => {
const [coordinates, setCoordinates] = useState([]);
const fetchCoords = async () => {
try {
const data = await axios
.get("http://localhost:8000/api/locations")
.then((reponse) => reponse.data["hydra:member"]);
setCoordinates(data);
} catch (error) {
toast.error("Impossible de charger les données");
}
};
useEffect(() => {
fetchCoords();
}, []);
const position = [49.442402, 1.09846];
return (
<>
<Map center={position} id="mapid" zoom={12}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
maxZoom="18"
id="mapbox/streets-v11"
/>
{coordinates.map((maps) => {
const ensemble = [maps.latitude, maps.longitude];
const adresse = maps.address;
return (
<Marker position={ensemble}>
<Popup>{adresse}</Popup>
</Marker>
);
})}
</Map>
</>
);
};
export default Maps;