Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React lifting state #2

Open
wants to merge 6 commits into
base: react-hooks
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,6 @@ Fetching data from API flow
5. Call the async function inside useEffect
6. Check my console.log and put the data in the state
7. Render something on the screen based on state

## Lifting state diagram
![Lifting state diagram](diagram.png)
Binary file added diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
56 changes: 52 additions & 4 deletions src/components/character-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,19 @@ const CharacterList = () => {
const [characters, setCharacters] = useState(null);

const getCharacters = async () => {
// Get the characters data from the API
const response = await axios.get('https://my-json-server.typicode.com/TechmongersNL/fs03-react/characters');
console.log(response.data);
setCharacters(response.data);

// We want to keep track of the number of "likes" for each character in our state now too
// Add our own "likes" key into each character object
const charactersWithLikes = response.data.map((character) => {
return {...character, likes: 0}
})
console.log(charactersWithLikes, 'character with likes')

// Each character, now with data from the API and our own "likes" data, is saved into the local React state
setCharacters(charactersWithLikes);
}

// If you don't put getCharacters in a useEffect hook, getCharacters will be called (and will make an Axios request) every time CharactersList gets re-rendered
Expand All @@ -22,26 +32,64 @@ const CharacterList = () => {
getCharacters();
}, []);

const increaseLikes = (id) => {
// when this function is called, I want to increase the amount of likes on that character
// in order to update a character, I need to use setCharacters

// to update the character: first we need to find the character that we want to update
// then make a copy of that character, and increase the amount of likes in it
// add that updatedCharacter back into our updatedArray
// setCharacter(updatedArray)
const updatedArray = characters.map((character) => {
if (character.id === id) {
return {...character, likes: character.likes + 1};
} else {
return character;
}
})
// console.log(characters, 'characters before update')
// console.log(updatedArray, 'characters after update');

setCharacters(updatedArray);
// console.log('increase likes was clicked with id: ' + id)
}

const getCharactersComponents = () => {
return characters.map((character, index) => {
return characters.map((character) => {
return (
<Character
key={index}
key={character.id}
name={character.name}
birthday={character.born}
blood={character.blood}
imgUrl={character.imgUrl}
quote={character.quote}
likes={character.likes}
increaseLikes={increaseLikes}
id={character.id}
/>
)
})
}

const calculateTotalLikes = () => {
let likesSum = 0;
characters.forEach((character) => {
likesSum = likesSum + character.likes;
})
return likesSum;
}

return (
// if characters data is not null (the initial value of the characters state variable)
// then I want to show Characters components
// else I want to show "loading..."
characters ? getCharactersComponents() : 'Loading...'
<>
<h4>Total number of likes: {characters ? calculateTotalLikes() : 'Loading...'}</h4>
<div>
{characters ? getCharactersComponents() : 'Loading...'}
</div>
</>
)
}

Expand Down
3 changes: 2 additions & 1 deletion src/components/character.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ const Character = (props) => {
<h2>Quote</h2>
<p>{props.quote}</p>
<Image url={props.imgUrl} />
<LikeCounter />
{/* Passing props from CharacterList even further down into LikeCounter */}
<LikeCounter likes={props.likes} increaseLikes={props.increaseLikes} id={props.id} />
<hr />
</>
)
Expand Down
26 changes: 17 additions & 9 deletions src/components/like-counter.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
import {useState} from 'react';
import '../styles/like-counter.css';

const LikeCounter = () => {
const [count, setCount] = useState(0);
const LikeCounter = (props) => {
// No more local state, it's now being passed in through props
//const [count, setCount] = useState(0);

const count = props.likes;
const increaseLikes = props.increaseLikes;
const [favorite, setFavorite] = useState(false);

const whenIncreaseButtonClicked = () => {
setCount(count + 1);
increaseLikes(props.id);
};
const whenDecreaseButtonClicked = () => {
if (count > 0) {
setCount(count - 1);
}
}

// Can you think of ways to make the decrease button work?
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you think of ways to make the decrease button still work?

// Option 1: Create a new decreaseLikes function in CharacterList, and pass it down through props
// Option 2: Pass a boolean variable (also called a "flag") to increaseLikes. When the value is true, increase likes by 1. When it's false, decrease likes by 1
// const whenDecreaseButtonClicked = () => {
// if (count > 0) {
// setCount(count - 1);
// }
// }

return (
<>
<div>
<h4>Number of likes: {count}</h4>
<button className={'buttonStyle'} onClick={whenIncreaseButtonClicked}>Like me!</button>
<button onClick={whenDecreaseButtonClicked}>Decrease likes</button>
{/* <button onClick={whenDecreaseButtonClicked}>Decrease likes</button> */}
</div>
<div>
<h4>{favorite && '⭐️'}</h4>
Expand Down