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

Api testing #1

Merged
merged 2 commits into from
May 19, 2024
Merged
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
142 changes: 89 additions & 53 deletions src/components/App.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,56 @@
import React, { useState } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import React, { useState, useEffect } from 'react';
import { useQueryClient, QueryClient, QueryClientProvider, useQuery } from 'react-query';
import './App.css';
import PersonCard from './PersonCard';
import ToggleButton from 'react-bootstrap/ToggleButton';
import ToggleButtonGroup from 'react-bootstrap/ToggleButtonGroup';

const queryClient = new QueryClient();

interface CharacterData {
id: string;
name: string;
height: string;
mass: string;
eye_color: string;
hair_color: string;
skin_color: string;
}

function App() {
return (
<QueryClientProvider client={queryClient}>
<GetPeople />
</QueryClientProvider>
)
}

function GetPeople() {
const [length, setLength] = useState<number>(12);
const [favoriteCards, setFavoriteCards] = useState<number[]>([]);
const [showFavorites, setShowFavorites] = useState<boolean>(false);

const queryClient = useQueryClient()

const { isLoading, error, data } = useQuery<CharacterData[]>('people', () =>
fetch('https://w5c9dy2dg4.execute-api.us-east-2.amazonaws.com/people', {
headers: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
},
}).then(res =>
res.json()
)
);

useEffect(() => {
if (data) {
setFavoriteCards(data.map(person => parseInt(person.id)));
}
}, [data]);

console.log(favoriteCards);

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const value = parseInt(event.target.value);
if (!isNaN(value)) {
Expand All @@ -21,7 +60,6 @@ function App() {
}
};

// Call AWS lambda to update DynamoDB here!!
const handleFavoriteToggle = (cardIndex: number) => {
setFavoriteCards(prevFavorites =>
prevFavorites.includes(cardIndex)
Expand All @@ -40,58 +78,56 @@ function App() {
: Array.from({ length }, (_, index) => index);

return (
<QueryClientProvider client={queryClient}>
<div className="App">
<header className="App-header">
<h2 className="App-title">SWAPI React + Typescript Test!</h2>
<a
className="SWAPI-link"
href="https://swapi.dev/"
target="_blank"
rel="noopener noreferrer"
>
Star Wars API
</a>
</header>
<div className="App-input">
<label htmlFor="lengthInput"># of People Cards Displayed:</label>
<input
type="number"
id="lengthInput"
value={length}
onChange={handleInputChange}
min="1"
max="50"
/>
</div>

<ToggleButtonGroup
className="toggle-buttons"
type="radio"
name="options"
defaultValue={1}
onChange={handleToggleChange}
<div className="App">
<header className="App-header">
<h2 className="App-title">SWAPI React + Typescript Test!</h2>
<a
className="SWAPI-link"
href="https://swapi.dev/"
target="_blank"
rel="noopener noreferrer"
>
<ToggleButton id="tbg-radio-1" value={1}>
All-Items
</ToggleButton>
<ToggleButton id="tbg-radio-2" value={2}>
Favorites
</ToggleButton>
</ToggleButtonGroup>

<div className="App-cards">
{displayedCards.map(index => (
<PersonCard
key={index}
index={index}
isFavorite={favoriteCards.includes(index)}
onFavoriteToggle={handleFavoriteToggle}
/>
))}
</div>
Star Wars API
</a>
</header>
<div className="App-input">
<label htmlFor="lengthInput"># of People Cards Displayed:</label>
<input
type="number"
id="lengthInput"
value={length}
onChange={handleInputChange}
min="1"
max="50"
/>
</div>
</QueryClientProvider>

<ToggleButtonGroup
className="toggle-buttons"
type="radio"
name="options"
defaultValue={1}
onChange={handleToggleChange}
>
<ToggleButton id="tbg-radio-1" value={1}>
All-Items
</ToggleButton>
<ToggleButton id="tbg-radio-2" value={2}>
Favorites
</ToggleButton>
</ToggleButtonGroup>

<div className="App-cards">
{displayedCards.map(index => (
<PersonCard
key={index}
index={index}
isFavorite={favoriteCards.includes(index)}
onFavoriteToggle={handleFavoriteToggle}
/>
))}
</div>
</div>
);
}

Expand Down
57 changes: 53 additions & 4 deletions src/components/PersonCard.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useQuery } from 'react-query';
import React from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import Card from 'react-bootstrap/Card';
import ToggleButton from 'react-bootstrap/ToggleButton';

Expand All @@ -9,6 +10,7 @@ interface PersonCardProps {
}

interface CharacterData {
id: string;
name: string;
height: string;
mass: string;
Expand All @@ -17,17 +19,58 @@ interface CharacterData {
skin_color: string;
}

function PersonCard({ index, isFavorite, onFavoriteToggle }: PersonCardProps): JSX.Element {
const addPerson = async (id: number, data: CharacterData): Promise<CharacterData> => {
data.id = id.toString();
const response = await fetch(`https://w5c9dy2dg4.execute-api.us-east-2.amazonaws.com/people`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
}

const deletePerson = async (id: number): Promise<void> => {
const response = await fetch(`https://w5c9dy2dg4.execute-api.us-east-2.amazonaws.com/people/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
},
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
}

function PersonCard({ index, isFavorite, onFavoriteToggle }: PersonCardProps): JSX.Element {
const queryClient = useQueryClient();
// api starts at 1 not 0
const person = index+1;
const person = index + 1;

const { isLoading, error, data } = useQuery<CharacterData>('getPerson_' + person, () =>
fetch('https://swapi.dev/api/people/' + person).then(res =>
fetch('https://swapi.dev/api/people/' + person).then(res =>
res.json()
)
);

const addMutation = useMutation((newData: CharacterData) => addPerson(index, newData), {
onSuccess: () => {
queryClient.invalidateQueries('getPerson_' + person);
},
});

const deleteMutation = useMutation(() => deletePerson(index), {
onSuccess: () => {
queryClient.invalidateQueries('getPerson_' + person);
},
});

if (isLoading) return (<p>Loading...</p>);

if (error) return (<p>Error fetching data.</p>);
Expand All @@ -43,6 +86,11 @@ function PersonCard({ index, isFavorite, onFavoriteToggle }: PersonCardProps): J
}

const handleFavoriteClick = () => {
if (isFavorite) {
deleteMutation.mutate();
} else {
addMutation.mutate(data);
}
onFavoriteToggle(index);
};

Expand All @@ -54,6 +102,7 @@ function PersonCard({ index, isFavorite, onFavoriteToggle }: PersonCardProps): J
variant={isFavorite ? 'primary' : 'outline-primary'}
value={1}
onClick={handleFavoriteClick}
disabled={addMutation.isLoading || deleteMutation.isLoading}
>
{isFavorite ? 'Unfavorite' : 'Favorite'}
</ToggleButton>
Expand Down
Loading