1

In a JS , I refer to a file on a remote server like :

class App extends Component {
constructor(props) {
    super(props);
    let client = this.getParameterByName('client', window.url);
    this.state = {
        sidebarClass: 'open',
        client: client ? client : 'abc-client',
        specUrl: client
            ? `http://<remote-host>/${client}.json`
            : '<remote-host>/abc-client.json',
    };
    this.showAPI = this.showAPI.bind(this);
    this.toggleSidebar = this.toggleSidebar.bind(this);
}
getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

showAPI(specURL) {
    this.setState({
        specUrl: 'http://<remotehost>/' + specURL + '.json',
        client: specURL,
    });
}
toggleSidebar() {
    this.setState((prevState) => ({
        sidebarClass: prevState.sidebarClass === 'open' ? '' : 'open',
    }));
}
render() {
    return (
        <div>
            <Sidebar
                showAPI={this.showAPI}
                toggleClass={this.state.sidebarClass}
                toggleSidebar={this.toggleSidebar}
                client={this.state.client}
            />
            <header className="header text-center">
                <div className="text-right">
                    <div className="hamburger" onClick={this.toggleSidebar}>
                        <svg
                            xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 30 30"
                            width="30"
                            height="30"
                            focusable="false">
                            <path
                                stroke="#c635d7"
                                strokeWidth="2"
                                strokeLinecap="round"
                                strokeMiterlimit="10"
                                d="M4 7h22M4 15h22M4 23h22"
                            />
                        </svg>
                    </div>
                    <h3 className="heading text-center">{this.state.client}</h3>
                </div>
            </header>
            <section className={`swagger-container ${this.state.sidebarClass}`}>
                <Swagger specUrl={this.state.specUrl} />
            </section>
        </div>


    );
    }
   }

Now, instead of a remote host, I want to bundle it in the react application itself (serve it locally). I understand that the file needs to be present in the public folder but did not understand how to reference it in the javaScript shared above.

2 Answers 2

1

You can use fetch for this. If your xxx.json is in the root of the public folder, use:

const data = fetch('xxx.json');

But why not put it in the src/data folder directly and load as:

import data from ‘./data/xxx.json’;

I think the second way reduces the need for a useless http request and also will potentially reduce the size of your code.

Sign up to request clarification or add additional context in comments.

Comments

0

In the next example you can see and array definite as DATA, it can be a response from your backend after axios or fetch request. You can define DATA to mock up responses in objects or arrays like do you prefer

import React, { useEffect, useState } from 'react';
import { View, Text, TextInput, StyleSheet, Dimensions, SafeAreaView, FlatList, TouchableOpacity, StatusBar } from 'react-native';
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/FontAwesome';
import Header from '../../core/Header/Header';
import DismissKeyboard from '../../libs/DismissKeyboard';
const { width: WIDTH } = Dimensions.get('window');
import Guide from './Guide';

const styles = StyleSheet.create({
  iconQr: {
    fontSize: 36,
    color: 'white',
  },
  inputContainer: {
    marginTop: 10,
  },
  input: {
    height: 45,
    fontSize: 16,
    paddingLeft: 45,
    borderRadius: 10,
    width: WIDTH - 55,
    marginHorizontal: 25,
    backgroundColor: '#FFFFFF',
  },
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight || 0,
  },
});

const DATA = [
  {
    "empresa": "SHIPNOW",
    "tipo_operacion": "ENTREGA",
    "bultos": 1,
    "sender_empresa": "SUCSHIPNOW",
    "sender_remitente": "SHIPNOW",
    "sender_direccion": "Av. de los Constituyentes 2985",
    "sender_localidad": "CABA",
    "sender_provincia": "CABA",
    "sender_cp": 1428,
    "comprador_apenom": "Lisandro Arguello",
    "comprador_direccion": "Calle Jun\u00edn 2189",
    "comprador_localidad": "Corrientes",
    "comprador_provincia": "Corrientes",
    "comprador_cp": 3400,
    "usuario:": "shipnow",
    "id:": 166308,
    "zonaOrigen:": "AMBA",
    "fecha_hora:": "2020-10-01 13:20:13",
    "zona:": "NEA",
    "confirmada:": 1,
    "tipo_op:": 0,
    "remito:": null,
    "servicio:": "ENVIO ECOMMERCE",
    "orden:": 1,
    "rrId:": 61972,
    "contrareembolso:": null,
    "codigo_estado:": "011"
  },
  { "empresa": "SHIPNOW", "tipo_operacion": "ENTREGA", "bultos": 1, "sender_empresa": "SUCSHIPNOW", "sender_remitente": "SHIPNOW", "sender_direccion": "Av. de los Constituyentes 2985", "sender_localidad": "CABA", "sender_provincia": "CABA", "sender_cp": 1428, "comprador_apenom": "Mellsa Picchio", "comprador_direccion": "Uruguay 1145", "comprador_localidad": "BBB", "comprador_provincia": "Corrientes", "comprador_cp": 3400, "usuario": "shipnow", "id": 165891, "zonaOrigen": "AMBA", "fecha_hora": "2020-09-30 07:24:41", "zona": "NEA", "confirmada": 1, "tipo_op": 0, "remito": null, "servicio": "ENVIO ECOMMERCE", "orden": 2, "rrId": 61973, "contrareembolso": null, "codigo_estado": "011" },
  { "empresa": "SHIPNOW", "tipo_operacion": "ENTREGA", "bultos": 1, "sender_empresa": "SUCSHIPNOW", "sender_remitente": "SHIPNOW", "sender_direccion": "Av. de los Constituyentes 2985", "sender_localidad": "CABA", "sender_provincia": "CABA", "sender_cp": 1428, "comprador_apenom": "Claudia Silva", "comprador_direccion": "Calle Playa Miramar 2754", "comprador_localidad": "Corrientes", "comprador_provincia": "Corrientes", "comprador_cp": 3400, "usuario": "shipnow", "id": 166152, "zonaOrigen": "AMBA", "fecha_hora": "2020-09-30 16:34:43", "zona": "NEA", "confirmada": 1, "tipo_op": 0, "remito": null, "servicio": "ENVIO ECOMMERCE", "orden": 3, "rrId": 61974, "contrareembolso": null, "codigo_estado": "011" },
  { "empresa": "SHIPNOW", "tipo_operacion": "ENTREGA", "bultos": 1, "sender_empresa": "SUCSHIPNOW", "sender_remitente": "SHIPNOW", "sender_direccion": "Av. de los Constituyentes 2985", "sender_localidad": "CABA", "sender_provincia": "CABA", "sender_cp": 1428, "comprador_apenom": "Claudia Silva", "comprador_direccion": "Azcuenga 1995", "comprador_localidad": "Corrientes", "comprador_provincia": "Corrientes", "comprador_cp": 3400, "usuario": "shipnow", "id": 166153, "zonaOrigen": "AMBA", "fecha_hora": "2020-09-30 16:34:43", "zona": "NEA", "confirmada": 1, "tipo_op": 0, "remito": null, "servicio": "ENVIO ECOMMERCE", "orden": 3, "rrId": 61974, "contrareembolso": null, "codigo_estado": "011" },
  { "empresa": "SHIPNOW", "tipo_operacion": "ENTREGA", "bultos": 1, "sender_empresa": "SUCSHIPNOW", "sender_remitente": "SHIPNOW", "sender_direccion": "Av. de los Constituyentes 2985", "sender_localidad": "CABA", "sender_provincia": "CABA", "sender_cp": 1428, "comprador_apenom": "Claudia Silva", "comprador_direccion": "Urquiza 2050", "comprador_localidad": "Corrientes", "comprador_provincia": "Corrientes", "comprador_cp": 3400, "usuario": "shipnow", "id": 166154, "zonaOrigen": "AMBA", "fecha_hora": "2020-09-30 16:34:43", "zona": "NEA", "confirmada": 1, "tipo_op": 0, "remito": null, "servicio": "ENVIO ECOMMERCE", "orden": 3, "rrId": 61974, "contrareembolso": null, "codigo_estado": "011" },
  { "empresa": "SHIPNOW", "tipo_operacion": "ENTREGA", "bultos": 1, "sender_empresa": "SUCSHIPNOW", "sender_remitente": "SHIPNOW", "sender_direccion": "Av. de los Constituyentes 2985", "sender_localidad": "CABA", "sender_provincia": "CABA", "sender_cp": 1428, "comprador_apenom": "Claudia Silva", "comprador_direccion": "Palmares Valley 50", "comprador_localidad": "Corrientes", "comprador_provincia": "Corrientes", "comprador_cp": 3400, "usuario": "shipnow", "id": 166155, "zonaOrigen": "AMBA", "fecha_hora": "2020-09-30 16:34:43", "zona": "NEA", "confirmada": 1, "tipo_op": 0, "remito": null, "servicio": "ENVIO ECOMMERCE", "orden": 3, "rrId": 61974, "contrareembolso": null, "codigo_estado": "011" },
]


function Delivieries({ navigation, route }) {
  const [selectedId, setSelectedId] = useState(null);
  const [guideNumber, setGuideNumber] = useState(null);

  useEffect(() => route.params?.guideNumber && setGuideNumber(route.params?.guideNumber)
    , [route.params?.guideNumber]);

  const renderGuide = ({ item, index }) => {
    console.log(item)
    const backgroundColor = item.id === selectedId ? "#FFFFFF" : "#FFFFFF";
    return (
      <Guide
        item={item}
        index={index}
        onPress={() => setSelectedId(item.id)}
        style={{ backgroundColor }}
      />
    );
  };

  return (
    <>
      <Header title="Entregas pendientes" isHome={false} />
      <View style={{ marginTop: 25, marginLeft: 30, paddingBottom: 5 }}>
        <Text>Ingresar número de ruta</Text>
      </View>
      <DismissKeyboard>
        <View style={{ flex: 0.1, alignItems: 'center', justifyContent: 'center' }}>
          <View style={styles.inputContainer}>
            <TextInput
              value={guideNumber}
              onChangeText={(guideNumber) => setGuideNumber(guideNumber)}
              placeholder="Número de ruta"
              underlineColorAndroid="transparent"
              placeholderTextColor="rgba(0,0,0,0.2)"
              style={styles.input}
            />
          </View>
        </View>
      </DismissKeyboard>
      <SafeAreaView style={styles.container}>
        <FlatList
          data={DATA}
          renderItem={renderGuide}
          keyExtractor={(item) => item.id}
          extraData={selectedId}
        />
      </SafeAreaView>
      <ActionButton
        buttonColor="rgba(231,76,60,1)"
        renderIcon={() => <Icon name="qrcode" style={styles.iconQr} />}
        onPress={() => navigation.navigate('Scanner')}
        position="center"
        size={55}
      />
    </>
  );
};

export default Delivieries;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.