so I am attempting to pass data to another state in React. Here's what happens -> on page load I grab my books from Google Books API I have the array of that book's data. I am trying to set the state of 4 things based off the data in the array. This is where I'm having trouble, it's not updating the state, and sometimes the Bookdetails page isn't grabbing it. Here is my main page function:
const viewBookDetails = bookNumber => props => {
// setBookID({ bookID: bookNumber });
console.log("Test test test");
console.log(coryBooks[bookNumber]);
setState({ title: coryBooks[bookNumber].volumeInfo.title, author: coryBooks[bookNumber].volumeInfo.author });
setState({ img: coryBooks[bookNumber].volumeInfo.img });
setState({ publisher: coryBooks[bookNumber].volumeInfo.publisher });
setState ({
publisher: "test"
});
console.log("state: ",state);
history.push({
pathname: '/Bookdetails',
state
});
};
when I console.log it, it says the data is "". Sometimes, and I mean completely randomly, sometimes the other page will get the data correct, and it updates accordingly, but I have no idea why. Here is my other page:
import '../App.css';
import Navigation from './Navigation';
import Milestone1part2 from './Milestone1part2';
import React, { useState, useEffect } from 'react';
import { useHistory, context, NavLink } from "react-router-dom";
const Bookdetails = props => {
const { title, author, img, publisher } =
(props.location && props.location.state);
const history = useHistory();
useEffect(() => {
console.log(title);
console.log(history.location.state);
}, []);
return (
<div>
<NavLink to="/" activeClassName="active">
Go Back
</NavLink>
<div className="form-details">
<div>
<strong>Publisher:</strong> {publisher}
</div>
</div>
</div>
);
};
export default Bookdetails;
edit 2: here is the code for my button which sends an int for the book number and calls the function "viewBookDetails"
{coryBooks.map(function (item, i) {
return <tr key={'item-' + i}> <td>{item.volumeInfo.title}</td><td> <a href={item.volumeInfo.previewLink}> <img src={item.volumeInfo.imageLinks.smallThumbnail} alt="image" /> </a>
<button type="submit" onClick={viewBookDetails(i) } > Book details </button> </td> </tr>
})}
edit: here is my entire main page code, SO editor giving me a hard time for formatting it here. https://pastebin.com/4VD8JqFn
Is there a better way to pass data between pages besides history? Why is my state not updating?
I have been ripping my hair out over this problem, any help is appreciated.