I believe that so far I have set up the input tags that the user will input the relevant things needed in order for me to pull out a picture from the NASA API. I don't think that the state that I have are getting the last inputted information and printing out to the console the URL from the user input. I think the problem may be with how I use state but I don't have an idea about how to do it even after I read the docs. Any help would be greatly appreciated.
import './App.css';
import React, { useState } from 'react';
const getCamera = (c) => {
const inputedCamera = c.target.value;
console.log(inputedCamera);
}
const getRover = (r) => {
const inputedRover = r.target.value;
console.log(inputedRover)
}
const getDate = (d) => {
const inputedDate = d.target.value;
console.log(inputedDate);
}
const constructURL = (camera, rover, date) => {
const userURL = "https://api.nasa.gov/mars-photos/api/v1/rovers/" + rover + "/photos?earth_date=" + date + "&camera=" + camera + "&api_key=DEMO_KEY";
console.log(userURL)
}
const App = () => {
const [photos, setPhotos] = useState("");
const [camera, setCamera] = useState("");
const [rover, setRover] = useState("");
const [date, setDate] = useState("");
const gettingInfo = () => {
fetch(constructURL(camera, rover, date))
.then((response) => {setPhotos(response.json()['photos'])}) //sets values for photos
.catch(() => console.log("Fetch Failed"))
};
return (
<div className="App">
<header className="App-header">
<div id='container'>
<div>
<input type="text" id="date-picker" name="date-picker" placeholder="Enter a date" onChange={getDate}></input>
<input type="text" id="rover" name="rover" placeholder="Enter a rover" onChange={getRover}></input>
<input type="text" id="camera" name="camera" placeholder="Enter a camera" onChange={getCamera}></input>
</div>
<button onClick={console.log(gettingInfo)}>URL generator</button>
</div>
</header>
<body>
</body>
</div>
);
}
export default App;
You're missing the value attribute inside the input tag. Use:
<input type="text" id="rover" name="rover" value={rover} placeholder="Enter a rover" onChange={getRover}></input>
I would also recommend that you move your methods i.e. getCamera, getRover, getDate inside the App function.
There's also a better approach by using only one state with all your attributes and replacing all the methods with only one method and then using value={state.rover} or whatever the name of that particular field is. It goes something like this:
const onInputChange = (event) => {
[event.target.name]: event.target.value
}
then using it like this: onChange={onInputChange}