akerbeltz
akerbeltz
Explore posts from servers
SSolidJS
Created by akerbeltz on 10/18/2023 in #support
children.forEach typescript problem
I have this problem in the forEach with typescript. Property 'forEach' does not exist on type 'ResolvedChildren'. Property 'forEach' does not exist on type 'number'.ts(2339)
export interface PropsDl {
children: JSX.Element;
}
const DescriptionList: Component<PropsDl> = (props) => {
const c = children(() => props.children);

createEffect(() => {
c().forEach((item, i) => {
if (i % 2 == 0) item.style = 'background-color:whitesmoke';
});
});

return (
<>
<div class='dl'> {c()}</div>
</>
);
};
export interface PropsDl {
children: JSX.Element;
}
const DescriptionList: Component<PropsDl> = (props) => {
const c = children(() => props.children);

createEffect(() => {
c().forEach((item, i) => {
if (i % 2 == 0) item.style = 'background-color:whitesmoke';
});
});

return (
<>
<div class='dl'> {c()}</div>
</>
);
};
46 replies
SSolidJS
Created by akerbeltz on 10/9/2023 in #support
Persist routes between reloads with @solidjs/router
It's strange but for some reason when i do a reload ( with an f5 for example), the direction changes to the root direction. Before, in other apps it persisted the route direction. Any ideas of what it can be?
3 replies
SSolidJS
Created by akerbeltz on 9/26/2023 in #support
Spinner component questions about best practices
What would be the best way to show a spinner only if a loading() signal spends more than 2 seconds (that is when a resource). I'm thinking setting that on the Spinner component directly but there's a better way? Also the spinner usually appears on each page of the app centered so I created a prop that wraps it in a div and centers it, rendered conditionally with the wrapper or alone, what do you thing?
import { Component, Show, createSignal, onCleanup, onMount } from 'solid-js';
import './Spinner.scss';

interface Props {
inPage: boolean;
}

const Spinner: Component<Props> = (props) => {
const [showSpinner, setShowSpinner] = createSignal();
const timeoutSpinner = setTimeout(() => {
setShowSpinner(true);
}, 1000);

onCleanup(() => {
clearTimeout(timeoutSpinner);
});

return (
<Show when={showSpinner()}>
<Show when={props.inPage} fallback={<div class='cir-spinner'></div>}>
<div style={{ 'max-width': '600px', 'height': '500px' }}>
<div
style={{
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
height: '100%',
}}
>
<div class='cir-spinner'></div>
</div>
</div>
</Show>
</Show>
);
};

export default Spinner;

import { Component, Show, createSignal, onCleanup, onMount } from 'solid-js';
import './Spinner.scss';

interface Props {
inPage: boolean;
}

const Spinner: Component<Props> = (props) => {
const [showSpinner, setShowSpinner] = createSignal();
const timeoutSpinner = setTimeout(() => {
setShowSpinner(true);
}, 1000);

onCleanup(() => {
clearTimeout(timeoutSpinner);
});

return (
<Show when={showSpinner()}>
<Show when={props.inPage} fallback={<div class='cir-spinner'></div>}>
<div style={{ 'max-width': '600px', 'height': '500px' }}>
<div
style={{
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
height: '100%',
}}
>
<div class='cir-spinner'></div>
</div>
</div>
</Show>
</Show>
);
};

export default Spinner;

3 replies
SSolidJS
Created by akerbeltz on 9/6/2023 in #support
Typing custom hooks
I made a custom hook for a post of a file, this is the code:
import axios from 'axios';

export const useUploadToOta = () => {
const [errorCode, setErrorCode] = createSignal('');
const [severity, setSeverity] = createSignal('');
const [loadingPost, setLoadingPost] = createSignal(false);
const [uploadProgress, SetUploadProgress] = createSignal(0);
let res;
const options = {
headers: {
'Content-Type': 'multipart/form-data',
},
onUploadProgress: (progressEvent) => {
let progress = Math.round((100 * progressEvent.loaded) / progressEvent.total);
console.log(progressEvent);
SetUploadProgress(progress);
},
};

async function postToOta(file) {
let formData = new FormData();
formData.append('file', file);
return await axios
.post('/ota/upload', formData, options)
.then((response) => {
if (response !== null) {
setSeverity('success');
} else {
setSeverity('warning');
setErrorCode('No response');
}
res = response;
})
.catch(function (error) {
res = 'error';
console.log(error);
setSeverity('warning');
setErrorCode(
error.response
? error.response.status
: error.request
? 'No response'
: error.message
? 'General error'
: 'General error'
);
})
.finally(() => {
setLoadingPost(false);
});
}
return [postToOta, errorCode, severity, loadingPost, uploadProgress];
};
import axios from 'axios';

export const useUploadToOta = () => {
const [errorCode, setErrorCode] = createSignal('');
const [severity, setSeverity] = createSignal('');
const [loadingPost, setLoadingPost] = createSignal(false);
const [uploadProgress, SetUploadProgress] = createSignal(0);
let res;
const options = {
headers: {
'Content-Type': 'multipart/form-data',
},
onUploadProgress: (progressEvent) => {
let progress = Math.round((100 * progressEvent.loaded) / progressEvent.total);
console.log(progressEvent);
SetUploadProgress(progress);
},
};

async function postToOta(file) {
let formData = new FormData();
formData.append('file', file);
return await axios
.post('/ota/upload', formData, options)
.then((response) => {
if (response !== null) {
setSeverity('success');
} else {
setSeverity('warning');
setErrorCode('No response');
}
res = response;
})
.catch(function (error) {
res = 'error';
console.log(error);
setSeverity('warning');
setErrorCode(
error.response
? error.response.status
: error.request
? 'No response'
: error.message
? 'General error'
: 'General error'
);
})
.finally(() => {
setLoadingPost(false);
});
}
return [postToOta, errorCode, severity, loadingPost, uploadProgress];
};
How can i type it so i don't have typescipt errors when i use this parts ? This is how i use it in the components:
const [postToOta, errorCode, severity, loadingPost, uploadProgress] = useUploadToOta();
const [postToOta, errorCode, severity, loadingPost, uploadProgress] = useUploadToOta();
And the use them like
<p>Upload at {uploadProgress()}%</p>
<p>Upload at {uploadProgress()}%</p>
13 replies
SSolidJS
Created by akerbeltz on 8/30/2023 in #support
typing CreateResource
I would like to do something like this so typescript don't show an error when using it in jsx: const [data, { mutate }] = createResource<{ dataExample: string } | undefined>(() => getData("/api/Example") ); So i can do: <p>{data()?.dataExample}</p>
44 replies
SSolidJS
Created by akerbeltz on 8/2/2023 in #support
How to reload a component in solidjs (a route or a specific component) (I'm using solidjs/router)
I need to be able to reload a component clicking a button or reload the whole route page clicking another button. I want the same functionality like doing a window.location.reload but more specific with a router page or a component.
8 replies
SSolidJS
Created by akerbeltz on 7/25/2023 in #support
Validating a field based on promise values min and max with yup and react form handler
const schemaReference = (res) => { console.log(res); return yup.object({ unit: yup.string().required('Required'), reference: yup .number() .typeError('Reference must be a number') .min(res.min, 'must be in the range ' + res.min +"-"+ res.max) .max(res.max, 'must be in the range ' + es.min+"-"+ res.max) .required('Required'), }); }; const getMinMax = async () => { let res = await initialData; let min = await res.data.parameters.min; console.log(min); let max = await res.data.parameters.max; console.log(max); return { min, max }; }; const formHandler = useFormHandler(yupSchema(schemaReference(getMinMax()))); This is the code on the body of a component. I want to basically pass a variable that is the response of an http request (so this is a promise and that implies a lot of async awaits everywere). Reading the doc of yup and solid form handler i didn't find a way to do that
3 replies
SSolidJS
Created by akerbeltz on 6/26/2023 in #support
signal of createResource is not reactive inside a For component
When passing the signal obtained in a request made by createResource and looping the results of that the reactivity when the resource mutate is lost. It works fine if i iterate the signal with a .map() so i don't know what can be the issue.
24 replies
SSolidJS
Created by akerbeltz on 6/5/2023 in #support
checkbox controlled from outside
I want to control a checkbox from the outside and expose either a function onChange and the props.checked that will be reactive. import { createSignal } from 'solid-js'; import c from './Switch.module.scss'; function SwitchButton(props) { return ( <div style={{ display: 'flex', }} > <div style={{ 'align-self': 'center' }}>{props.label1}</div> <label class={c.switch}> <input type={'checkbox'} class={c.input} checked={props.checked} onChange={(e) => props?.onChange?.(e)} /> <span class={c.slider}></span> </label> <div style={{ 'align-self': 'center' }}>{props.label2}</div> </div> ); } export default SwitchButton;
29 replies
SSolidJS
Created by akerbeltz on 5/24/2023 in #support
problem with "use:" and custom directives in tsx
I copied the custom directive from the docs
import { onCleanup } from 'solid-js';
export default function clickOutside(el, accessor) {
const onClick = (e) => !el.contains(e.target) && accessor()?.();
document.body.addEventListener('click', onClick);
onCleanup(() => document.body.removeEventListener('click', onClick));
}
import { onCleanup } from 'solid-js';
export default function clickOutside(el, accessor) {
const onClick = (e) => !el.contains(e.target) && accessor()?.();
document.body.addEventListener('click', onClick);
onCleanup(() => document.body.removeEventListener('click', onClick));
}
and then I used here like this
<div
class='select-component'
onClick={toggleDropdown}
use:clickOutside={() => setIsOpen(false)}
>
<div
class='select-component'
onClick={toggleDropdown}
use:clickOutside={() => setIsOpen(false)}
>
But it marks as a error when I use it like that in the tsx file. It works correctly as expected tho. Is there any way to get rid of the wavy red line ? The error says:
Type '{ children: Element[]; class: string; onClick: () => void; "use:clickOutside": () => false; }' is not assignable to type 'HTMLAttributes<HTMLDivElement>'. Property 'use:clickOutside' does not exist on type 'HTMLAttributes<HTMLDivElement>'.
9 replies
SSolidJS
Created by akerbeltz on 4/26/2023 in #support
CreateLocalStorage hook problem with reactivity
I'm trying to make a custom hook that exposes a signal and uses the LocalStore of the browser.
import { Signal, createSignal } from "solid-js";

function createStoredSignal<T>(key: string, defaultValue: T, storage = localStorage): Signal<T> {
const initialValue = storage.getItem(key)
? (JSON.parse(storage.getItem(key)) as T)
: defaultValue;

const [value, setValue] = createSignal<T>(initialValue);

const setValueAndStore = ((arg) => {
const v = setValue(arg);
storage.setItem(key, JSON.stringify(v));
return v;
}) as typeof setValue;

return [value, setValueAndStore];
}
export default createStoredSignal;
import { Signal, createSignal } from "solid-js";

function createStoredSignal<T>(key: string, defaultValue: T, storage = localStorage): Signal<T> {
const initialValue = storage.getItem(key)
? (JSON.parse(storage.getItem(key)) as T)
: defaultValue;

const [value, setValue] = createSignal<T>(initialValue);

const setValueAndStore = ((arg) => {
const v = setValue(arg);
storage.setItem(key, JSON.stringify(v));
return v;
}) as typeof setValue;

return [value, setValueAndStore];
}
export default createStoredSignal;
the problem is this don't seem to work with reactivity.
25 replies
SSolidJS
Created by akerbeltz on 4/19/2023 in #support
Websockets on Solidjs
I have some code in React for websocket conexion in components, I tried to port the code to solidjs, but no success yet.
// Websockets
onMount(() => {
const initWebSocket = () => {
let hostname = window.location.hostname;
console.log(hostname);
if (hostname === "localhost") ws = new WebSocket("ws://localhost:5000/");
else ws = new WebSocket("ws://" + hostname + "/api/events/ws");

console.log(ws);
ws.onclose = onClose;
ws.onmessage = onMessage;
ws.onerror = onError;
};

const onClose = (e) => {
setTimeout(initWebSocket, 2000);
};

const onError = (event) => {
console.error("Error:" + event);
};

// Listener websocket message
//////////////////////////////////////////////////
const onMessage = (e) => {
console.log(e.data);
};
initWebSocket();
});
// Websockets
onMount(() => {
const initWebSocket = () => {
let hostname = window.location.hostname;
console.log(hostname);
if (hostname === "localhost") ws = new WebSocket("ws://localhost:5000/");
else ws = new WebSocket("ws://" + hostname + "/api/events/ws");

console.log(ws);
ws.onclose = onClose;
ws.onmessage = onMessage;
ws.onerror = onError;
};

const onClose = (e) => {
setTimeout(initWebSocket, 2000);
};

const onError = (event) => {
console.error("Error:" + event);
};

// Listener websocket message
//////////////////////////////////////////////////
const onMessage = (e) => {
console.log(e.data);
};
initWebSocket();
});
Any idea of how would look this to work correctly? the idea of the websockets is to update an http resource (I think I'll use the mutate of the createResource API)
35 replies
SSolidJS
Created by akerbeltz on 4/17/2023 in #support
How to implement an ErrorHandle to wrap the handle error and loading of a resource?
I want to handle both the error and loading of a resource in the same component to wrap a page with this comonent so it renders a message error when there's one and loading when it's loading. Something like that but don't get the right sintax.

import { Component, Show, children} from "solid-js";
import Alert from "./Alert";

const ErrorHandle: Component = (props) => {
const c = children(() => props.children);
return (
<Show
when={!props.data.error}
fallback={
(props.data.error && <Alert severity="warning"> {props.data.error?.message}</Alert>) ||
"loading..."
}
>
{c}
</Show>
);
};

export default ErrorHandle;

import { Component, Show, children} from "solid-js";
import Alert from "./Alert";

const ErrorHandle: Component = (props) => {
const c = children(() => props.children);
return (
<Show
when={!props.data.error}
fallback={
(props.data.error && <Alert severity="warning"> {props.data.error?.message}</Alert>) ||
"loading..."
}
>
{c}
</Show>
);
};

export default ErrorHandle;
1 replies
SSolidJS
Created by akerbeltz on 4/9/2023 in #support
If the prop array can be an object or a string. Which method would you use ?
This is the code that renders the props.items that prop can be either an array of objects with a text titles and an icon or only an array of text titles. Also how would you do validation ? The code i wrote works correctly but there's a better way? <Index each={props.items}> {(item, index) => ( <A href={ props.hrefRoot + (typeof item() === "string" ? item() : item().text) } activeClass="router-link-active" inactiveClass="" class="carousel-item" > <Show when={item().icon}> <span class={"icon icon-" + item().icon} /> </Show> {typeof item() === "string" ? item() : item().text} </A> )} </Index>
2 replies
SSolidJS
Created by akerbeltz on 4/5/2023 in #support
Adding eventListener in an onMount shows error in console
I created a form ref and added an event listener in a component with tsx ´´´ let formRef; . . .
onMount(() => { console.log(formRef); formRef.addEventListener("input", (e) => { if (e.target.name !== "enable") { setIsJustSubmitted(false); } }); }); <form ref={formRef} onSubmit={submit}> . . . ´´´ The form gets printed a lot of times and the error i get is "Uncaught (in promise) TypeError: formRef is undefined" I tried multiple things but none did work, like trying to catch the error, making the event listener be added conditionally when the formRef is filled etc
28 replies
SSolidJS
Created by akerbeltz on 4/5/2023 in #support
refetch not changing the signal of the createResource
when trying to update the data of the signal of a resource it didn't update. I have the same issue with mutate. I'm missing something ?
2 replies