Skip to content

Instantly share code, notes, and snippets.

@martinwairegi
Created March 10, 2022 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinwairegi/ea88e569224eceb46020cca674ed38af to your computer and use it in GitHub Desktop.
Save martinwairegi/ea88e569224eceb46020cca674ed38af to your computer and use it in GitHub Desktop.
import create from 'zustand';
import { nanoid } from 'nanoid';
const getLocalStorage = (key) => JSON.parse(window.localStorage.getItem(key));
const setLocalStorage = (key, value) =>
window.localStorage.setItem(key, JSON.stringify(value));
export const useStore = create((set) => ({
texture: 'dirt',
cubes: getLocalStorage('world') || [],
addCube: (x, y, z) =>
set((state) => ({
cubes: [
...state.cubes,
{ key: nanoid(), pos: [x, y, z], texture: state.texture },
],
})),
removeCube: (x, y, z) => {
set((state) => ({
cubes: state.cubes.filter((cube) => {
const [_x, _y, _z] = cube.pos;
return _x !== x || _y !== y || _z !== z;
}),
}));
},
setTexture: (texture) => {
set((state) => ({
texture,
}));
},
saveWorld: () =>
set((state) => {
setLocalStorage('world', state.cubes);
}),
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment