Skip to content

Instantly share code, notes, and snippets.

@Artfunkel
Created June 10, 2021 18:02
Show Gist options
  • Save Artfunkel/54d9d66bdd0b817d59894353a2449f19 to your computer and use it in GitHub Desktop.
Save Artfunkel/54d9d66bdd0b817d59894353a2449f19 to your computer and use it in GitHub Desktop.
import React, { Reducer, useEffect, useReducer, useState } from 'react';
import { Button } from 'reactstrap';
export class WrappedIncrementorState {
current: number = 0;
max: number = 0;
}
export type WrappedIncrementorAction =
| { type: 'INCREMENT' }
| { type: 'SETMAX', payload: number }
export const wrappedIncrementor = (oldState: WrappedIncrementorState, action: WrappedIncrementorAction) => {
let state = { ...oldState }
switch (action.type) {
case 'INCREMENT':
state.current++;
if (state.current >= state.max) {
state.current = 0;
}
break;
case 'SETMAX':
state.max = action.payload;
if (state.current >= state.max) {
state.current = state.max - 1;
}
break;
}
return state;
}
export const ImageGallery = () => {
const [image, setImage] = useState<string | null>()
const [index, setIndex] = useReducer(wrappedIncrementor, new WrappedIncrementorState())
const fetchNewImage = async () => {
setImage(null)
let response = await fetch(`imagegallery/${index.current}`);
setIndex({ type: 'SETMAX', payload: parseInt(response.headers.get("total-images") as string) })
const fileReaderInstance = new FileReader();
fileReaderInstance.readAsDataURL(await response.blob());
fileReaderInstance.onload = () => {
setImage(fileReaderInstance.result as string);
}
}
useEffect(() => { fetchNewImage() }, [index.current])
return (
<>
<Button onClick={() => setIndex({ type: 'INCREMENT' })} disabled={image == null}>Next image</Button>
<div style={{ border: '2px solid black', width: 1024, height: 768 }}>
{image == null ? (<p>Loading...</p>) : (<img src={image} style={{ display: 'block', height: '100%', width: '100%', objectFit: 'contain' }} />)}
</div>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment