I can load csv files from external URL, but when I try to load a file that the user uploaded to the web, it shows an empty Object.
The object appears to be loaded, but you can`t access the information in any way. The solutions I found online were to setup servers, but I didn't want to do that. I want to have an client-side only web app with tensorflowJS.
main.js:
export default function Main() {
const [archivo, setArchivo] = useState();
const cargarArchivo = (archivo) => {
setArchivo(archivo);
};
async function realizarCalculos() {
await preprocesamiento(archivo);
}
return (
<div>
<Dropzone cargarArchivo={cargarArchivo} />
<Button
onClick={realizarCalculos}
style={{ margin: "5vh" }}
variant="outlined"
>
Calcular Caudales
</Button>
</div>
);
}
Dropzone.js:
class Dropzone extends Component {
constructor(props) {
super(props);
this.state = {
files: [],
};
}
handleChange(files) {
this.props.cargarArchivo(files[0]);
this.setState({
files: files,
});
}
render() {
return (
<DropzoneArea
acceptedFiles={[".csv"]}
onChange={this.handleChange.bind(this)}
/>
);
}
}
export default Dropzone;
Tensorflow JS:
import * as tf from "#tensorflow/tfjs";
export async preprocesamiento(archivo){
const csvDataset = tf.data.csv(archivo.path);
}
TensorflowJS tf.data.csv works with fetch under the hood. Meaning that you can't load local files, see this question. I resolved the issue by creating an URL object with the URL class, and serving the url to tensorflow :
import * as tf from "#tensorflow/tfjs";
export async preprocesamiento(archivo){
const url = URL.createObjectURL(archivo);
const csvDataset = tf.data.csv(url);
}
Related
Sorry for being noob but I am really confused on how to work on this. So I followed the instructions on this https://github.com/i18next/next-i18next but confused when it comes to index.js. Whenever I click my toggle switch for /de in my landing page it translates alright in url "http://localhost:3000/de".
But in another page like "About" or in any other page it doesn't translate but the url switch to "http://localhost:3000/de/about". It doesnt go to my 404 error page. But I don't get it why it doesn't translate.
In my index.js if I removed "Service" component which contained all the components of landing page. And replace with other component file like "About" component page it translate alright.
It seems "http://localhost:3000/de" url only works in translation. But in different url path it doesn't. How to do this? Thank you..
Kindly see my code..
My locales path
public/locales/de/common.json
src/pages/_app.js
import nextI18NextConfig from '../../next-i18next.config'
<Component {...pageProps} />
export default appWithTranslation(App, nextI18NextConfig);
src/pages/index.js
import React from 'react';
import Service from 'views/Service';
import i18nextConfig from '../../next-i18next.config';
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
const IndexPage = () => {
return (
<Service/> <— this contains my landing page the only can be translated as “localhost:/3000/de” (src/pages/views/service)
)
};
export async function getServerSideProps({ locale }) {
return { props: {
...(await serverSideTranslations(locale, ['common', 'footer', 'stripe', ‘navbar'], i18nextConfig))
} }
}
export default IndexPage;
in my navbar it is in global component I put my toggle language switcher
src/layouts/Main/components/Navbar/Navbar.js
const onToggleLanguageClick = (locale) => {
const { pathname, asPath, query } = router
router.push({ pathname, query }, asPath, { locale })
}
const changeTo = router.locale === 'de' ? 'en' : 'de'
return (
<button onClick={() => onToggleLanguageClick(changeTo)}>
{t('change-locale', { changeTo })}
</button>
)
this is my next-i18next.config
const path = require('path');
module.exports = {
i18n: {
locales: ['en', 'de'],
defaultLocale: 'en',
localePath: path.resolve('./public/locales')
},
}
my next.config.js
const nextConfig = {
i18n,
…some code
}
module.exports = nextConfig
src/pages/_document.js
import i18nextConfig from '../../next-i18next.config';
export default class MyDocument extends Document {
render() {
const currentLocale = this.props.__NEXT_DATA__.query.locale ?? i18nextConfig.i18n.defaultLocale;
return (
<Html lang={currentLocale}>
.....
First of all, remove the second argument in the appWithTranslation. There is also no need to change the language in the html tag (src/pages/_document.js). i18 does it itself.
public/locales/en ---common.json & /de ---common.json
Wrong. Use the default paths 'public/locales/en/common.json'. Also you can remove the 'localePath' in i18 config file.
reference: https://github.com/i18next/next-i18next
I figured out my problem. Got confused with many of my file paths. Maybe it can help someone.
Add these to your component
export async function getServerSideProps({ locale }) {
....code
}
that doesn't translate your "http://localhost:3000/de/componentname", which in the obvious path: src/pages/componentname.js
... just like my src/pages/index.js above.
I have the following where I am able to print the data coming from getServerSideProps.
But when I pass it on to the component section, the prop value posts is undefined. Why?
The following is under /pages and is inside the base index.tsx file.
import type { NextPage } from 'next'
import Post from '../components/Post'
const Home: NextPage = ({ posts }) => {
// This prints undefined. This is the issue.
console.log(posts)
return (
<div>
<Post posts={posts}/>
</div>
)
}
export default Home
export const getServerSideProps = async () => {
const response = await fetch('http://localhost:8080/posts/all')
const data = await response.json()
// this prints correctly
console.log(data)
return {
props: {
posts: data
}
}
};
Updates to show _app.tsx file
import Home from '../pages';
const TestApp = () => {
return <>
<Home />
</>
}
export default TestApp
Remove the custom _app.tsx file or update it to accept a Component prop and render it as shown in the Nextjs documentation for a Custom App.
The problem is this custom App is always rendering the Home component (with no props) so it's printing undefined. Then, try navigating to / on localhost. It should render the index.tsx file and properly invoke getServerSideProps and pass the result to the component as you expect.
Basically, I will try to use tsparticles JSON file in my react project that I export from https://particles.js.org/. but it was not working.
I have used particle js in my project. In my project, I have made a separate component and called this component inside the main component like the App.js
And I have made the JSON file as an API. If you want to make the JSON file into an API or also you can directly call this API.
import React from "react";
import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";
const ParticleAnimation = () => {
const particlesInit = async (main) => {
console.log(main);
await loadFull(main);
};
const particlesLoaded = (container) => {
console.log(container);
};
return (
<div>
<Particles
id="tsparticles"
url={YOUR_JSON_FILE_LINK_HERE}
init={particlesInit}
loaded={particlesLoaded}
/>
</div>
);
};
export default ParticleAnimation;
I am learning how to implement Lingui(i18n) on apps. Everything is setup, but I wanted to know how I should create a language swticher to change between language catalogs on my app.
This is my index.js file
import React, { useEffect } from "react";
import { render } from "react-dom";
import App from "./App";
import { I18nProvider } from "#lingui/react";
import { i18n } from "#lingui/core";
import { defaultLocale, dynamicActivate } from "./i18n";
const Translation = () => {
useEffect(() => {
dynamicActivate(defaultLocale);
}, []);
return (
<I18nProvider i18n={i18n}>
<App />
</I18nProvider>
);
};
render(<Translation />, document.getElementById("root"));
My App.js file
import "./App.css";
import { Trans } from "#lingui/macro";
function App() {
return (
<div className="App">
<header className="App-header">
<h1>
<Trans>HELLOO</Trans>
</h1>
<p>
<Trans>it's me.</Trans>
</p>
</header>
</div>
);
}
export default App;
and i18n.ts file
import { i18n } from '#lingui/core';
export const locales = {
en: "English",
es: "Spanish",
fr: "French",
};
export const defaultLocale = "fr";
/**
* We do a dynamic import of just the catalog that we need
* #param locale any locale string
*/
export async function dynamicActivate(locale: string) {
const { messages } = await import(`./locales/${locale}/messages`)
i18n.load(locale, messages)
i18n.activate(locale)
}
everytime I specify a es,en or fr defaultLocale the language changes, but I would like to have a language button to change this automatically on the page with select.
ex: "export const defaultLocale = "fr";" (in i18n.ts)
You can use i18n.activate() method to switch to needed locale.
i18n object API is defined in #js-lingui/core.
You also need to load the locale if it was not loaded before.
In case of your project you can use handy dynamicActivate() function you've already created.
Your component output will look like this:
<div>
<Trans>Switch to:</Trans>
<button
onClick={() => dynamicActivate('en')}>
English
</button>
<button
onClick={() => dynamicActivate('fr')}>
Français
</button>
<button
onClick={() => dynamicActivate('es')}>
Espanol
</button>
</div>
It will render 3 buttons [English] [Français] [Espanol] each one will load and activate needed locale.
It is a best practice to keep the button captions in their own languages, so users can find a language they understand.
As an addition to the above it probably makes sense to highlight currently-selected language and disable the button.
I'm using useLingui() to get i18n.locale which indicates current language and set disabled flag on one of the buttons bellow.
Here is the full code of LanguageSelector.js component for you, you can use it in App.js as <LanguageSelector />. Good luck with your project/learnings.
import React from "react"
import { useLingui } from "#lingui/react"
import { Trans } from "#lingui/macro";
import { dynamicActivate } from "./i18n";
const LanguageSelector = () => {
const { i18n } = useLingui();
return <div>
<Trans>Switch to:</Trans>
<button
onClick={() => dynamicActivate('en')}
disabled={i18n.locale === 'en'}>
English
</button>
<button
onClick={() => dynamicActivate('fr')}
disabled={i18n.locale === 'fr'}>
Français
</button>
<button
onClick={() => dynamicActivate('es')}
disabled={i18n.locale === 'es'}>
Espanol
</button>
</div>
};
export default LanguageSelector
UPDATED:
Additionally you can persist selected locale to browser's LocalStorage
We should save locale each time the dynamicActivate() gets called:
const LOCAL_STORAGE_KEY = 'lang';
function dynamicActivate(locale: string) {
// existing code here
window.localStorage.setItem(LOCAL_STORAGE_KEY, locale);
}
Apparently the #lingui/detect-locale library has very good coverage for detecting locale from many sources, including LocalStorage.
Here's how it can be applied here:
import { detect, fromUrl, fromStorage, fromNavigator } from '#lingui/detect-locale';
// existing code from i18n.ts
export const locales = {
en: "English",
es: "Spanish",
fr: "French",
};
export const defaultLocale = "en";
const LOCAL_STORAGE_KEY = 'lang';
// checks that detected locale is available
const isLocaleValid = (locale: string | null) => `${locale}` in locales;
// returns locale
export function getLocale() {
const detectedLocale = detect(
fromUrl("lang"), // for example http://localhost:3000/?lang=es
fromStorage(LOCAL_STORAGE_KEY),
fromNavigator(), // from system settings
() => defaultLocale,
);
return isLocaleValid(detectedLocale) ? detectedLocale : defaultLocale;
}
The last step is to call getLocale() instead of using defaultLocale all the time.
useEffect(() => {
// With this method we dynamically load the catalogs
dynamicActivate(getLocale());
}, []);
Gatsby noob here so please bear with me. I have a component that accepts props from the index.js where it is supposed to receive data from an array of objects but will always receive the error TypeError: Cannot read property 'map' of undefined where it's referring to the Hero.js component index.js is calling for.
My assumption is that the data being queried in index.js is either not specific enough or that it is rendering the component before data is received. Here is the index.js file:
import { graphql } from 'gatsby';
import { Layout, SEO, Hero } from 'components';
const IndexPage = ({ data }) => {
const dataFetch = data.contentfulTemplateIndex.heroes;
let tester = () => {
for (let count = 0; count < dataFetch.length; count++) {
return <Hero {...props} />;
}
};
console.log(dataFetch);
let props = {
impactText: dataFetch.impactText,
labels: dataFetch.labels,
primaryLabel: dataFetch.primaryLabel,
location: dataFetch.location
// supportingText: dataFetch.supportingText.json
};
return (
<Layout>
{dataFetch && tester()}
</Layout>
);
};
export const query = graphql`
query {
contentfulTemplateIndex {
heroes {
image {
fluid {
src
}
}
impactText
labels
location
primaryLabel
supportingText {
json
}
}
}
}
`;
export default IndexPage;
Here is the Hero.js component which index.js is calling:
import { Link } from 'gatsby';
import { documentToReactComponents } from '#contentful/rich-text-react-renderer';
import cx from 'classnames';
import styles from './hero.module.scss';
const Hero = (props) => {
return (
<div>
<ul>
<Link className={styles.pills}>{props.primaryLabel}</Link>
{props.labels.map((label) => {
return <Link className={styles.pills}>{label}</Link>;
})}
</ul>
<div className={styles.grid}>
<h1>{props.impactText}</h1>
</div>
</div>
);
};
export default Hero;
It's impossible for an outsider to debug your code without a minimum reproducable example.
The best way to debug GraphQL is to use the GraphiQL interface of your browser.
Run gatsby develop. If it fails because of the TypeError remove the lines of code that cause the type error (but not the code of your GraphQL query!). You need to get your development server runnning.
Open your browser, use the URL: http://localhost:8000/___graphql
Copy your graphQL query from your code and paste it into the GraphiQL query window.
Can you access your data there? If not you made a mistake writing your query or the data is not where it's supposed to be.
This way you can make sure the data exists.
It also helps to console.log(props) so you can examine the data object:
const Hero = (props) => {
console.log(props);
return (