import { EventActionEnum , SetEventsAction , SetGuestsAction } from "./types" ; import { IUser } from "../../../models/IUser" ; import { IEvent } from "../../../models/IEvent" ; import { AppDispatch } from "../../index" ; import UserService from "../../../api/UserService" ; export const EventActionCreators = { setGuests : ( payload ) : SetGuestsAction => ( { type : EventActionEnum . SET_GUESTS , payload } ) , setEvents : ( payload ) : SetEventsAction => ( { type : EventActionEnum . SET_EVENTS , payload } ) , fetchGuests : ( ) => async ( dispatch ) => { try { const response = await UserService . getUsers ( ) ; dispatch ( EventActionCreators . setGuests ( response . data ) ) ; } catch ( e ) { console . log ( e ) ; } } , createEvent : ( event ) => async ( dispatch ) => { try { const events = localStorage . getItem ( "events" ) || '[]' ; const json = JSON . parse ( events ) as IEvent [ ] ; json . push ( event ) ; dispatch ( EventActionCreators . setEvents ( json ) ) ; localStorage . setItem ( 'events' , JSON . stringify ( json ) ) ; } catch ( e ) { console . log ( e ) ; } } , fetchEvents : ( username ) => async ( dispatch ) => { try { const events = localStorage . getItem ( "events" ) || '[]' ; const json = JSON . parse ( events ) as IEvent [ ] ; const currentUserEvents = json . filter ( ev => ev . author === username || ev . guest === username ) ; dispatch ( EventActionCreators . setEvents ( currentUserEvents ) ) ; } catch ( e ) { console . log ( e ) ; } } } ;