Gieß Den Kiez

State Refactoring

Pain Points
Gathering the state

The all mighty

const user = store.getSate().user;

The good lad

const { user } = useStoreState('user')

Pain Points
Altering the state

The cheater

const createUser = store.action(createUser(store));

createUser(userId);

The very lazy fox

store.setState({ user: ... });

The good boy

const { createUser } = useActions(Actions)

createUser(userId);

Pain Points
Async mess

The typical situation

const Component = ({ apple }: any): any => {
  	const { eatFruit } = useAction(Actions);
    const [fruitColor, setFruitTaste] = useState<Generic>(0);
  	const { user } = useAauth0();
  
  	const onClick = (): any => {
      const changeData = async () => {
        eatFruit()
        store.setState({ fruitTaste: null });
        setFruitTaste(null);
      }
      changeData();
    }
  
	return (
      <Banana
      	fruit={fruitColor ? apple : undefined}
		toggle={(e) => onClick(e)}
      />
    )  
}

The typical situation

const Component = ({ apple }: any): any => {
  	const { eatFruit } = useAction(Actions);
    const [fruitColor, setFruitTaste] = useState<Generic>(0);
  	const { user } = useAauth0();
  
  	const onClick = (): any => {
      const changeData = async () => {
        eatFruit()
        store.setState({ fruitTaste: null });
        setFruitTaste(null);
      }
      changeData();
    }
  
	return (
      <Banana
      	fruit={fruitColor ? apple : undefined}
		toggle={(e) => onClick(e)}
      />
    )  
}

🤬

The typical situation

const Component = ({ apple }: any): any => {
  	const { eatFruit } = useAction(Actions);
    const [fruitColor, setFruitTaste] = useState<Generic>(0);
  	const { user } = useAauth0();
  
  	const onClick = (): any => {
      const changeData = async () => {
        eatFruit()
        store.setState({ fruitTaste: null });
        setFruitTaste(null);
      }
      changeData();
    }
  
	return (
      <Banana
      	fruit={fruitColor ? apple : undefined}
		toggle={(e) => onClick(e)}
      />
    )  
}

🤬

The typical situation

Mixed ways to work with data

Bad naming

No types, any or Generic

Using lazy shortcuts

Using store as a global object

Using Component to provoke side effects

Refactoring strategy

Extract fetching function into own utils

Get rid of async functions

Convert use of store.setState into actions

Restructure state

Convert store into Context

Use ReactQuery to fetch async data

Current status

Extract fetching function into own utils

Get rid of async functions

Convert use of store.setState into actions

Restructure state

Convert store into Context

Use ReactQuery to fetch async data

Made with Slides.com