Home > Enterprise >  How to get an arbitrary DRF Context Variable in React
How to get an arbitrary DRF Context Variable in React

Time:07-27

I'm having an issue with how to access arbitrary variables being sent from DRF backend to React frontend along with an actual serializer from a model. There are some objects I create in backend that I need to be able to send to the frontend. In regular django with vanilla js I send using JsonResponse({'object': object}) and I get the object from the response object after doing an ajax call. I can't figure out how to do the same thing using React.

Have searched all over and can't find anything to help show how to do this using the below react/redux process. I won't waste your time showing my failed attempts.

In my views.py using drf arbitrary context Goal is to be able to access some_object from view below in the frontend.

@api_view(['GET'])
def getProducts(request):
    products = Product.objects.all()
    some_object = 'this is a test'
    serializer = ProductSerializer(products, many=True, context={'some_object': some_object})
    return Response(serializer.data)

Actions.js

export const listProducts = () => async (dispatch) => {
  try {
      dispatch({ type: PRODUCT_LIST_REQUEST })

      const {data} = await axios.get('/api/products/')

      dispatch({
          type: PRODUCT_LIST_SUCCESS,
          payload: data
      })

Reducer.js

export const productListReducer = (state = { products: [] }, action) => {
    switch (action.type) {
        case PRODUCT_LIST_REQUEST:
            return { loading: true, products: [] }

        case PRODUCT_LIST_SUCCESS:
            return { loading: false, products: action.payload }

        case PRODUCT_LIST_FAIL:
            return { loading: false, error: action.payload }

        default:
            return state
    }
}

Screen.js

function HomeScreen() {
    const dispatch = useDispatch()
    const productList = useSelector(state => state.productList)
    const { error, loading, products } = productList

    useEffect(()=>{
        dispatch(listProducts())
        console.log({some_object})
    }, [dispatch])

    return (
        <div>
           {{some_object}}
        </div>
    )
}

export default HomeScreen


CodePudding user response:

The use of context is to access that value at the serializer

if u want send value to your ui

@api_view(['GET'])
def getProducts(request):
    products = Product.objects.all()
    some_object = 'this is a test'
    serializer = ProductSerializer(products, many=True, context={'some_object': some_object})
    return Response({data:serializer.data,my_value:some_object})
  • Related