This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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