S
SolidJS4mo ago
sh1man

Can anyone tell me how best to do it? Store API

import axios from "axios";
import {ErrorApi} from "~/utils/tryCallApi";
import {IBaseResponse, UserProfileEntity} from "~/types";
import {getCookieValue} from "~/utils";
import {type Navigator} from "@solidjs/router";
import {paths} from "~/utils/paths";

export type HttpClientActions = {
user: HttpClientActionsProfile
}

type HttpClientActionsProfile = {
profile: () => Promise<IBaseResponse<UserProfileEntity>>;
}

export default function createHttpClient(navigate: Navigator) {

const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
withCredentials: true,
headers: {
Accept: 'application/json',
}
})

api.interceptors.request.use((config) => {
const csrfToken = getCookieValue('csrftoken');
if (csrfToken !== null) {
config.headers['X-CSRFToken'] = csrfToken;
}
return config;
})

api.interceptors.response.use(
async (response) => response,
async (error) => {
if(error?.response?.status === 401){
/// This normal practice ????????????????????
setTimeout(() => {
navigate(paths.logIn);
}, 0);
}
const apiError: ErrorApi = {
message: error?.response?.data?.detail,
data: error?.response?.data,
status: error?.response?.status,
result: false
}
return Promise.reject(apiError);
}
)

const httpClient: HttpClientActions = {
user: {
profile: async () => api.post('/user/profile/'),
}
}

return httpClient;
}
import axios from "axios";
import {ErrorApi} from "~/utils/tryCallApi";
import {IBaseResponse, UserProfileEntity} from "~/types";
import {getCookieValue} from "~/utils";
import {type Navigator} from "@solidjs/router";
import {paths} from "~/utils/paths";

export type HttpClientActions = {
user: HttpClientActionsProfile
}

type HttpClientActionsProfile = {
profile: () => Promise<IBaseResponse<UserProfileEntity>>;
}

export default function createHttpClient(navigate: Navigator) {

const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
withCredentials: true,
headers: {
Accept: 'application/json',
}
})

api.interceptors.request.use((config) => {
const csrfToken = getCookieValue('csrftoken');
if (csrfToken !== null) {
config.headers['X-CSRFToken'] = csrfToken;
}
return config;
})

api.interceptors.response.use(
async (response) => response,
async (error) => {
if(error?.response?.status === 401){
/// This normal practice ????????????????????
setTimeout(() => {
navigate(paths.logIn);
}, 0);
}
const apiError: ErrorApi = {
message: error?.response?.data?.detail,
data: error?.response?.data,
status: error?.response?.status,
result: false
}
return Promise.reject(apiError);
}
)

const httpClient: HttpClientActions = {
user: {
profile: async () => api.post('/user/profile/'),
}
}

return httpClient;
}
4 Replies
sh1man
sh1man4mo ago
Main context
import {createContext, JSXElement, Resource, useContext} from 'solid-js';
import {createStore } from 'solid-js/store';
import createUser, {UserActions} from '~/store/createUser';
import createHttpClient from "~/store/createHttpClient";
import {useNavigate} from "@solidjs/router";
import {IBaseResponse, UserProfileEntity} from "~/types";

export interface AppState {
user: Resource<IBaseResponse<UserProfileEntity>>;
appName: string;
}
type AppActions = UserActions; // & AuthActions

type AppStore = [AppState, AppActions];

export type AppContextProps = {
store: AppStore;
}

const StoreContext = createContext<AppContextProps>();

export function StoreContextProvider(props:{ children: JSXElement }) {
const [state, setState] = createStore<AppState>({
get user() {
return user;
},
appName: 'pdf-parser'
});

const navigate = useNavigate();
const httpClient = createHttpClient(navigate);

const { user, userActions } = createUser(state, setState, httpClient);


const actions = { ...userActions };

const store: AppStore = [state, actions];

return (
<StoreContext.Provider value={{ store }}>
{props.children}
</StoreContext.Provider>
);

}

export function useStore() {
const context = useContext(StoreContext)
if (!context) {
throw new Error("useStore: cannot find a StoreContext")
}
return context.store;
}
import {createContext, JSXElement, Resource, useContext} from 'solid-js';
import {createStore } from 'solid-js/store';
import createUser, {UserActions} from '~/store/createUser';
import createHttpClient from "~/store/createHttpClient";
import {useNavigate} from "@solidjs/router";
import {IBaseResponse, UserProfileEntity} from "~/types";

export interface AppState {
user: Resource<IBaseResponse<UserProfileEntity>>;
appName: string;
}
type AppActions = UserActions; // & AuthActions

type AppStore = [AppState, AppActions];

export type AppContextProps = {
store: AppStore;
}

const StoreContext = createContext<AppContextProps>();

export function StoreContextProvider(props:{ children: JSXElement }) {
const [state, setState] = createStore<AppState>({
get user() {
return user;
},
appName: 'pdf-parser'
});

const navigate = useNavigate();
const httpClient = createHttpClient(navigate);

const { user, userActions } = createUser(state, setState, httpClient);


const actions = { ...userActions };

const store: AppStore = [state, actions];

return (
<StoreContext.Provider value={{ store }}>
{props.children}
</StoreContext.Provider>
);

}

export function useStore() {
const context = useContext(StoreContext)
if (!context) {
throw new Error("useStore: cannot find a StoreContext")
}
return context.store;
}
Raqueebuddin Aziz
Best do what?
sh1man
sh1man4mo ago
this is normal practice setTimeout(() => { navigate(paths.logIn); }, 0);
Raqueebuddin Aziz
Yes it is in some cases It's when you want to defer the execution till the next event loop run
Want results from more Discord servers?
Add your server
More Posts
Export Vercel Functions config on @solidjs/start@0.5.9Hello ! I've managed to update my `0.3.0` project to `0.5.9` by scooping info here and there on the How do I upgrade a solid-start project to use the latest version of solid-startI found a project that uses solid-start and actually has a working PWA. But it is from february 2023React is not defined when using custom server directory for ViteHi! If I use custom directory on the same level as `src` for dev mode in Vite & Solid setup, I get `solid-router without SSR and without having to redirectI just found out that when i build my app with solid-router its only possible to visit the index pagPortals in nested routes not rendering in consistent orderCheck out this stackblitz: https://stackblitz.com/edit/solidjs-templates-wwykia Loading `/one/two/thHow do I use solid router in the solid playground?I added solid router to the importmap, but whenever trying to import something it says “Cannot find how to make two-way data transfer through components?I need to pass a value from a child component to a parent component and back again and idk how to maIs createRouteAction removed ? Or Replaced ?Hi, I just updated my version of solid-start and cannot find `createRouteAction` in the docs. Can anPassing "up" signals in SolidI am trying to understand how can you go by reading values from signals defined in children componenuseNavigate - navigate(path) throws "computations created outside a `createRoot`" and errorSometimes (not 100% of the time) when a user selects a new category in the UI, the following code se